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 configure token Authentication of jwt in django

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

Share

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

This article mainly introduces how to configure jwt token authentication in django, which is very detailed and has certain reference value. Friends who are interested must read it!

1. Brief introduction to jwt

Json web token (JWT) is an open standard based on JSON (RFC 7519) for passing declarations between network application environments. The token is designed to be compact and secure and is particularly suitable for single sign-on (SSO) scenarios at distributed sites. The declaration of JWT is generally used to transfer authenticated user identity information between the identity provider and the service provider in order to obtain resources from the resource server, and can also add some additional declaration information necessary for other business logic. The token can also be directly used for authentication or can be encrypted.

2. Jwt composition

Jwt is a string consisting of three pieces of information, which are used in the text. Chained together to form a jwt string, like this:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

The first part we call it the head (header), the second part we call it the payload (similar to the objects carried on the plane), and the third part is the signature.

Header

The header of jwt carries two pieces of information:

a. Declare the type, this is jwt

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

The complete head looks like the following JSON:

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

The header is then encrypted with base64 (the encryption can be decrypted symmetrically) to form the first part.

EyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9payload

Load is the place where valid information is stored. The name seems to refer to the goods carried. These valid information consists of three parts.

a. Declaration of registration in the standard

b. A public statement

c. Private declaration

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

Iss: issuer of jwt

Sub: the user for which jwt is targeted

Aud: the party that receives the jwt

Exp: the expiration time of jwt, which must be greater than the issuing time

Nbf: defines when the jwt is not available

Iat: the issuing time of the jwt

Jti: the unique identity of jwt, which is mainly used as an one-time token to avoid playback.

Public statements: public statements can add any information, generally adding user-related information or other necessary information needed by the business, but it is not recommended to add sensitive information, because this part can decrypt private statements on the client side: private statements are jointly defined by providers and consumers, and it is generally not recommended to store sensitive information, because base64 is symmetrically decrypted. It means that this part of the information can be classified as plaintext information.

Define a payload:

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

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

Header (after base64)

Payload (after base64)

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.

/ / javascriptvar encodedString = base64UrlEncode (header) +'.'+ base64UrlEncode (payload); var signature = HMACSHA256 (encodedString, 'secret'); / / TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Use these three parts. Concatenate into a complete string to form the final jwt:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ Note: secret is stored on the server side, and the issuance and generation of jwt is also on the server side. Secret is used for jwt signing and jwt verification, so it is your server's private key and should not be disclosed in any scenario. Once the client knows about the secret, it means that the client can sign the jwt itself.

Django-rest-framework-jw documentation website

Install and configure JWT1. Install pip install djangorestframework-jwt2. Add the following to the configuration file dev.py: REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': (' rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication',' rest_framework.authentication.BasicAuthentication',),} import datetimeJWT_AUTH = {'JWT_EXPIRATION_DELTA': datetime.timedelta (days=1),}

JWT_EXPIRATION_DELTA specifies the validity period of token

3. The method of manually issuing JWT is provided in the documentation for the Django REST framework JWT extension from rest_framework_jwt.settings import api_settingsjwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLERjwt_encode_handler = api_settings.JWT_ENCODE_HANDLERpayload = jwt_payload_handler (user) token = jwt_encode_handler (payload)

After the user registers or logs in successfully, return the user information in the serializer and return token at the same time.

4. Django REST framework JWT provides a view to log in to obtain token, which can be used directly

In child routes, configure routes:

From rest_framework_jwt.views import obtain_jwt_tokenurlpatterns = [path ('login/', obtain_jwt_token),] 5. In the main route, introduce the routing file urlpatterns = [path ('users/', include ("users.urls")) of the current sub-application, the value of # include must be in the format of module name .urls, and only one dot can appear in the middle of the string] above is all the contents of the article "how to configure token authentication of jwt in django". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow 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