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

How to use JWT of Python

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, the editor will share with you the relevant knowledge points about how to use Python's JWT. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

1. JWT introduction

Jwt (JSON Web Tokens), an industry standard developed by RFC 7519, is used to securely represent statements between two parties. At present, jwt is widely used in the user authentication of the system, especially in the front and rear separation projects.

Jwt certification process:

In the development of a project, authentication is generally carried out according to the process shown in the figure above, that is, after the user has successfully logged in, the server returns a token to the user's browser. Later, the user's browser has to carry the token to send the request to the server, and the server verifies the validity of the token. If it is legal, it will show the user the data, otherwise, some error messages will be returned.

What is the difference in authentication between traditional token and jwt?

Traditional token method: after the user logs in successfully, the server generates a random token to the user, and saves a token in the server (database or cache). Later, the user needs to bring the token to visit. After the server receives the token, it goes to the database or cache to verify whether the token is timeout and legal.

Jwt mode: after the user logs in successfully, the server generates a random token to the user through jwt (the server does not need to keep the token). Later, the user needs to bring the token to visit again. After the server receives the token, the server verifies whether the token times out and is legal through jwt.

2. The principle of creating token2.1 JWT by JWT

The generated token format of jwt is as follows, that is, by. The composition of three concatenated strings

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lI

IwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

The generation rules are as follows:

The first part of HEADER, which always contains algorithm and token type, encrypts the json with base64url, which is token.

The first paragraph of

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

The second PAYLOAD section, which contains some data, encrypts the json with base64url. This is the second segment of the token.

{"sub": "1234567890", "name": "John Doe", "iat": 1516239022.}

The third paragraph SIGNATURE part, pass the base64url ciphertext of the first two paragraphs. Splice it together, then encrypt it with HS256, then encrypt the hs256 ciphertext with base64url, and finally get the third paragraph of token.

Base64url (HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), your-256-bit-secret (secret key plus salt)

Finally, three strings are passed. Spliced together to generate the token of jwt

Note: base64url encryption is to do base64 encryption first, and then-replace + and _ replace /

2.2 principle of JWT check token

Generally, after successful authentication, the token generated by jwt is returned to the user. Later, users need to carry token when they visit again. In this case, jwt needs to time out and verify the validity of the token.

After obtaining the token, the following steps are used for verification:

Divide token into three parts: header_segment, payload_segment and crypto_segment

JWT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" signing_input, crypto_segment = JWT_TOKEN.rsplit ('.', 1) header_segment, payload_segment = signing_input.split ('., 1)

Decrypt the first part of header_segment with base64url to get header

Decrypt the second part of payload_segment with base64url to get payload.

Decrypt the third part of crypto_segment by base64url, get signature, and verify the validity of part of the signature data.

Concatenate the first two paragraphs of ciphertext, namely: signing_input

Get the encryption algorithm from the first paragraph of plaintext. Default: HS256

Use algorithm + salt to encrypt signing_input, and compare the result with signature ciphertext.

3. Code implementation

Creating token of jwt based on pyjwt module of Python

Installation

Pip3 install pyjwt

Realize

From datetime import datetime, timedeltaimport jwtclass JwtToken (object): _ salt = "@ ^ 4 _ 00wedv**pi) + (! w1rwi=d3q4l=ie=g-u$s8jevmj*zgg2h" _ expire_message = dict (code=1200, msg= "token has failed") _ unknown_error_message = dict (code=4200, msg= "token resolution failure") @ classmethod def generate_token (cls, payload: dict)-> str: headers = dict (typ= "jwt", alg= "HS256") resut = jwt.encode (payload=payload Key=cls._salt, algorithm= "HS256", headers=headers) return resut @ classmethod def parse_token (cls, token: str)-> tuple: verify_status = False try: payload_data = jwt.decode (token, cls._salt Algorithms= ['HS256']) verify_status = True except jwt.ExpiredSignatureError: payload_data = cls._expire_message except Exception as _ err: payload_data = cls._unknown_error_message return verify_status, payload_dataif _ name__ = =' _ main__': TEST_DATA = dict (name= "mooor" Exp=datetime.utcnow ()-timedelta (seconds=1) token = JwtToken.generate_token (TEST_DATA) print (token) payload = JwtToken.parse_token (token) print (payload)

Note: exp must choose UTC time

Expiration time will be compared to the current UTC time (as given by timegm (datetime.utcnow (). Utctimetuple (), so be sure to use a UTC timestamp or datetime in encoding

4. Example: import jwtimport datetimedic = {'exp': datetime.datetime.utcnow () + datetime.timedelta (days=1), # expiration time' iat': datetime.datetime.utcnow (), # start time 'iss':' ChaosMoor', # signature 'data': {# content Generally store the user's id and start time 'asides: 1,' breadth: 2,},} token = jwt.encode (dic, 'secret', algorithm='HS256') # encrypted generation string print (token) payload = jwt.decode (token,' secret', issuer='lianzong', algorithms= ['HS256']) # decryption, verify the signature print (s) print (type (s))

Dic has an officially designated key, and the program will determine whether it is legal according to the Value of key when decrypting it. These key include:

"exp": when generating a token, you can set the validity time of the token. If we set it to expire within 1 day, the token will be thrown if we parse the token after 1 day.

Jwt.exceptions.ExpiredSignatureError: Signature has expired

"nbf": it refers to the effective time of the token. If it is used but before the effective time, it will be thrown:

Jwt.exceptions.ImmatureSignatureError: The token is not yet valid (nbf)

"iss": the issuer of token, we can give him a string. Note that iss has no problem if it is not checked when receiving. If we need to check but the signature is inconsistent when we receive it, it will throw a

Jwt.exceptions.InvalidIssuerError: Invalid issuer

"aud": the receiver is specified. The receiver must provide the same receiver (string) as required by token. If the receiver is not written or the receiver is inconsistent, it will be thrown.

Jwt.exceptions.InvalidAudienceError: Invalid audience

"iat": the start time of the token, if the current time is before the start time

Jwt.exceptions.InvalidIssuedAtError: IssuedAt claim (iat) cannot be in the future.

These are all the contents of the article "how to use Python's JWT". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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