Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the points for attention in Python security certification?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What are the points for attention in Python security certification? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Those things about python production field safety certification.

System security may often be ignored by everyone. Many of our systems say that "streaking" on the Internet is not exaggerated at all and are vulnerable to attack. System security is actually a complex and huge topic. If you want to talk about it in detail, you can't finish it with several books. Based on this article and the next one, we will focus on some security verification mechanisms encountered in the process of developing our system. I hope it can play a role in attracting jade. I hope you will think a lot in the process of development, not limited to the realization of the function.

There are usually a variety of ways to deal with system security, authentication and authorization, but most of them are complex. In many frameworks and systems, the work related to security and authentication is often tedious, and the amount of code is huge, based on which there are some related protocols and libraries. Let's take a look at the relevant content today.

one

Common authentication specifications / protocols

1.1

OAuth3

OAuth3 is a protocol specification that defines several processing methods for authentication and authorization. It is an extensible protocol specification that covers several complex usage scenarios. And it includes processing methods based on third-party authentication. The underlying technology of our common third-party login methods, such as "logging in using Wechat" and "logging in using QQ", is based on OAuth3.

1.2

OpenID Connect

OpenIDConnect is another OAuth3-based protocol specification. It extends some of the functions of OAuth3, making previously relatively vague functions more operable. The common Google login is based on OpenID Connect.

1.3

OpenAPI

OpenAPI is a set of open standards for building API. FastAPI is built on OpenAPI.

OpenAPI supports the following security mechanisms:

1.apiKey: apply the specified key from the

(1) query parameters

(2) header information

(3) cookie information

2.http: supports standard http authentication systems, including:

Bearer: header information Authorization contains Bearer and token information, inherited from OAuth3

HTTP basic Certification

HTTP Digest Certification

3.oauth3

4.openIdConnect

Through the introduction of fastapi.security module, FastAPI can support all of the above security mechanisms and simplify the use of it.

two

JWT

2.1

The concept of JWT

JSON Web Token (JWT) is a very lightweight specification. This specification allows us to use JWT to communicate secure and reliable information between the user and the server.

2.2

The composition of JWT

A JWT is actually a string that consists of three parts: the header, the payload, and the signature. Use these three paragraphs of information text. The links together make up the Jwt string. It's like this: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Head (Header)

The header of JWT carries two pieces of information:

1. Declare the type. This is jwt.

2. Declare the encryption algorithm, usually using HMAC SHA256 directly

Let's parse the eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 substring using base64 to get:

{"typ": "JWT", "alg": "HS256"}

It can be seen that the signature algorithm is indicated in the header as HS256 algorithm.

2.3

Load (Payload)

Load is the place where valid information is stored. This valid information consists of three parts.

1. Declaration registered in the standard

2. Public statement

3. Private declaration

Declaration of registration in the standard (recommended but not mandatory):

1. Iss (Issuer): issuer

2. Sub (Subject): theme

3. Aud (Audience): audience

4. Exp (Expiration Time): expiration time, which must be greater than the issuance time

5. Nbf (Not Before): effective time

6. Iat (Issued At): time of issuance

7. Jti (JWT ID): the unique identity of JWT, which is mainly used as an one-time token to avoid replay attacks.

Public statement:

Public statements can add any information, generally adding relevant information about the user or other necessary information needed by the business. However, it is not recommended to add sensitive information because this part can be decrypted on the client side.

Private declaration:

Private declaration is a declaration jointly defined by providers and consumers, and it is generally not recommended to store sensitive information, because base64 is symmetrically decrypted, which means that this part of the information can be classified as plaintext.

We can parse the eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9 using base64 to get a previously defined payload:

{"sub": "1234567890", "name": "John Doe", "admin": true}

2.4

Signature (Signature)

The third part of JWT is a visa information, which consists of three parts:

1. Header (after base64)

2. Payload (after base64)

3 、 secret

This part requires the use of base64 encrypted header and base64 encrypted payload. Concatenate the string, then add salt secret combination encryption through the encryption declared in header, and then form the third part of the JWT.

Signature = HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret); Token = base64 (head). Base64 (load). Signature

Note: secret is stored on the server side and should not be exposed in any scenario.

2.5

Use

Add Authorization to the request header headers and mark it with Bearer

Headers = {... 'Authorization':' Bearer'+ token...}

three

Authentication process of Token based on JWT

3.1

Login authentication process

1. First authentication: when the user logs in for the first time, the user enters the user name / password from the browser, and the Action layer (Login Action) of the login process to the server after submission.

2.Login Action calls the authentication service to authenticate the user name and password. If the authentication is passed, the LoginAction layer calls the user information service to obtain user information (including complete user information and corresponding permission information).

3. After returning the user information, Login Action obtains the secret key information generated by Token signature from the configuration file to generate Token

4. In the process of generating Token, you can call a third party's JWT Lib to generate signed JWT data.

5. After signing the JWT data, set it to the COOKIE object and redirect it to the home page to complete the login process

Let's take a look at the whole authentication process of login through the complete picture:

3.2

Request authentication

1. The Token-based authentication mechanism carries the Token information that completes the signature in each request, which may be in the COOKIE or in the Authorization header of the HTTP

two。 The client (APP client or browser) requests access to the resource (page or call API) through GET or POST

3. The authentication service intercepts the request as a Middleware HOOK. It first looks for Token information in COOKIE, and if it cannot find it, it looks for it in HTTP Authorization Head.

4. If the Token information is found, the JWT Lib is called to decrypt and decode the Token information according to the signed encryption key in the configuration file

5. After completing the decoding and verifying the signature, verify the exp, nbf, aud and other information in Token.

6. After all is passed, the permission logic judgment of the requested resource is made according to the role permission information obtained by the user.

If the permission logic is judged to pass, it is returned through the Response object; otherwise, HTTP 401 is returned

Let's take a look at the whole login request authentication process through the complete picture:

3.3

Summary of Token authentication based on JWT:

1. A Token is a collection of information, a string of information.

two。 Include enough information in the Token to reduce the chances of querying the database in subsequent requests

3. The server needs to check the Token information of COOKIE and HTTP Authrorization Header.

4. Based on the above point, you can use a set of Token authentication codes to face browser clients and non-browser clients.

5. Because Token is signed, we can assume that a Token that can be decoded and authenticated is issued by our system, and the information contained in it is legal and valid.

four

Get Token actual combat

Before we write the code, let's take a look at the functionality of the class OAuth3PasswordBearer. OAuth3PasswordBearer is a class that takes URL as a parameter: the client sends username and password parameters to the URL and gets a Token value. OAuth3PasswordBearer does not create the corresponding URL path operation, but simply indicates the target URL that the client uses to get the Token.

When the request arrives, FastAPI checks the requested Authorization header information. If no Authorization header information is found, or if the content of the header information is not Bearer Token, it returns a 401 status code (UNAUTHORIZED). Let's know each other again from the source code:

Class OAuth3PasswordBearer (OAuth3): def _ init__ (self, tokenUrl: str, scheme_name: str = None, scopes: dict = None, auto_error: bool = True,): if not scopes: scopes = {} flows= OAuthFlowsModel (password= {"tokenUrl": tokenUrl, "scopes": scopes}) super (). _ _ init__ (flows=flows, scheme_name=scheme_name Auto_error=auto_error)

Async def _ call__ (self, request: Request)-> Optional [str]: authorization: str = request.headers.get ("Authorization") scheme, param = get_authorization_scheme_param (authorization) if not authorization or scheme.lower ()! = "bearer": if self.auto_error: raise HTTPException Detail= "Not authenticated", headers= {"WWW-Authenticate": "Bearer"},) else: return None return param

In order to complete our next function, we need to install these two modules:

Pip install pyjwtpip install python-multipart

A brief explanation:

Pyjwt is used to generate and verify JWT token

Python-multipart is because OAuth3 needs to send username and password information through form data

In the production practice, get the code of token:

From datetime import datetime, timedeltafrom typing import Optional

From fastapi import Depends, FastAPIfrom fastapi.security import OAuth3PasswordBearer, OAuth3PasswordRequestFormimport jwtfrom pydantic import BaseModel

# to get a string like this run:# openssl rand-hex 32SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30

Class Token (BaseModel): access_token: str token_type: str

App = FastAPI ()

# oauth3_scheme = OAuth3PasswordBearer (tokenUrl= "/ token")

# generate tokendef create_access_token (data: dict, expires_delta: Optional [timedelta] = None): to_encode = data.copy () if expires_delta: expire = datetime.utcnow () + expires_delta else: expire = datetime.utcnow () + timedelta (minutes=15) to_encode.update ({"exp": expire}) encoded_jwt = jwt.encode (to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt

# request API @ app.post ("/ token", response_model=Token) async def login_for_access_token (form_data: OAuth3PasswordRequestForm = Depends (): access_token_expires = timedelta (minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token (data= {"sub": "test"}, expires_delta=access_token_expires) return {"access_token": access_token, "token_type": "bearer"}

Let's run the code to see the effect:

Let's take a look at the composition of each part by parsing access_token:

1. The parsing result of the substring "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" is:

two。 The parsing result of the substring "eyJzdWIiOiJ0ZXN0IiwiZXhwIjoxNjE4MTExNTA4fQ" is:

3. The parsing result of the substring "pwoiwQmQZbIFVvmdlmkSPXdoHrtZyoNNTRhoWAZWU9o" is:

This is the answer to the questions about Python security certification. I hope the above content can help you to a certain extent. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report