Django REST framework JWT learning

1.JWT learning

After the user registration or login, we want to record the user's login status, or create authentication credentials for the user. We no longer use the Session authentication mechanism, use Json Web Token authentication mechanism.

Json web token (JWT), is a statement in order to pass between the network application execution environment based on open standards JSON ((RFC 7519). The token is designed to be compact and safe, especially for single-distributed sites sign-on (SSO) scenario .JWT statements are typically used to provide and service providers transfer between the user identity is authenticated identity information in order to obtain resources from the server, you can also add some extra other business logic that must be statement information, the token can be directly used for authentication may be encrypted.

1.1 jwt composition

JWT on a string, consisting of three pieces of information, use these three pieces of information text .with links constitute Jwt string. like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

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

1.1.1 header

jwt head carries two pieces of information:

  • Declared type, here is jwt

  • Assertion of the encryption algorithm is usually used directly HMAC SHA256

Complete head like this in JSON:

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

Then the head base64-encryption (the encrypted can be decrypted symmetric), constitutes the first portion.

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

1.1.2 payload

Load local storage is valid information. The name refers specifically to such goods carried on the aircraft, these effective information consists of three parts

  • Standard registration statement

  • Public Statement

  • Private statement

Standard registration statement (recommended, but not mandatory to use):

  • ISS : jwt issuer

  • Sub : JWT for the user

  • AUD : the receiving side jwt

  • exp : jwt expiration time, the expiration date must be greater than the issue of time

  • NBF : What time is defined before the jwt are not available.

  • IAT : jwt the issue of time

  • the JTI : jwt unique identity, is mainly used as a one-time token, in order to avoid a replay attack.

Public statement : public declarations can add any information, general information about the user to add the necessary information or other business needs, but is not recommended for sensitive information to add, because the part of the client can decrypt.

Private statement : Private statement is a statement providers and consumers as common definition, is generally not recommended to store sensitive information, because base64 is decrypted symmetric, meaning that some of the information may be classified as plaintext.

Define a payload:

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

Then base64-encrypted, to give a second portion of the JWT.

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

1.1.3 signature

JWT is the third part of a visa information, this visa information consists of three parts:

  • header (after the base64)

  • payload (after the base64)

  • secret

And after base64 after the header part needs to encrypt the encrypted payload using base64 .string concatenation composition, and then by salt encryption header declared in secretcombination encryption, and the third portion constitutes the jwt.

// JavaScript If you want to generate analog jwttoken, may be employed to generate the following code [Note: The pseudo-code] 
var encodedString = base64UrlEncode (header) + ' . ' + Base64UrlEncode (payload); 

var Signature = HMACSHA256 (encodedString, ' Secret ' ); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

These three parts with .a full string connected, constitutes the final jwt:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Note: secret is stored on the server side, the issue generated jwt also on the server side, secret is used to authenticate the issuance and jwt of jwt, so it is your server's private key, in any scenario should not be revealed to go. Once the client has learned the secret, it means that the client can be self-signed jwt up.


For issuing and verification of JWT, we can use Django REST framework JWT extension to complete.

Documentation website http://getblimp.github.io/django-rest-framework-jwt/

1.2 django installed configuration JWT

1.2.1 Installation

pip install djangorestframework-jwt

1.2.2 setting in the configuration file

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}

Note: JWT_EXPIRATION_DELTA specified token valid

1.3 Generating jwt

Django REST framework JWT extension of the documentation provides a method of manual issued by JWT

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)

After the user registration or login is successful, it returns the user information in the serializer in the future and returns token can be.

2. Based on the jwt achieve certification front and rear ends

2.1 back-end implementation login authentication interface

In sub-application users in routing urls.py

from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    path(r'authorizations/', obtain_jwt_token, name='authorizations'),
]

Next, we can test the following functions by postman

1553572597916

2.2 front end to save jwt

We can JWT saved in a cookie can also be stored in the local memory of the browser, we saved in the browser local storage

Local store browser provides sessionStorage and localStorage two ways:

  • sessionStorage browser is closed shall lapse

  • localStorage long-term effective

Instructions

sessionStorage. variable name = variable value // save data 
sessionStorage. variable names   // read data 
sessionStorage.clear ()   // remove all sessionStorage saved data 

localStorage. variable name = variable value // save the data 
localStorage. variable name   // read data 
localStorage.clear ()   // clears all data stored in localStorage

More than 2.3 landing conditions

JWT extended login view, when you receive a user name and password, but also to call Django's authentication system provided authenticate () to check the user name and password are correct.

We can support the login account by modifying the authentication backend Django authentication system (primarily authenticate method) can be either a user name or a phone number.

Modify authentication backend Django authentication system needs to inherit django.contrib.auth.backends.ModelBackend, and override the authenticate method.

authenticate(self, request, username=None, password=None, **kwargs)Parameter Description method:

  • The request authentication request object

  • username user account this certification provided

  • This provides password authentication password

We want to let users either log in as the user name, you can also log in to the phone number, then for the authenticate method, username parameter means that the user name or phone number.

Rewrite ideas authenticate method:

  1. According to locate the user User object parameter username, the username parameter may be a user name, it may be the phone number

  2. If it can find the User object, call check_password method to check whether the correct password User object

Write in users / utils.py in:

from django.contrib.auth.backends Import ModelBackend
 from .models Import the User
 from django.db.models Import Q
 Import Re 

DEF get_user_by_account (the Account):
     "" " acquisition model based on user account information " "" 
    the try :
         # IF re.match ( '^. 1 [3-9] \ {D} $. 9', Account): 
        #      # phone number 
        #      user = User.objects.get (= Mobile Account) 
        # the else: 
        #      # username 
        #      user = User.objects .get (username = Account) 

        UserUser.objects.get = (Q (Mobile = the Account) | Q (username = the Account)) 

    the except User.DoesNotExist: 
        the User = None 

    return the User 


class UsernameMobileAuthBackend (ModelBackend):
     DEF the authenticate (Self, Request, username = None, password = none, ** kwargs):
         # log to determine 
        the User = get_user_by_account (username) 

        # accounts have to be verified by a password, and a good judge whether the current station is an active state 
        iF isinstance (the User, the User) and user.check_password (password ) and self.user_can_authenticate (the User):
             return the User

Django settings.py informed in the configuration file used in our custom authentication backend

AUTHENTICATION_BACKENDS = [
    'users.utils.UsernameMobileAuthBackend',
]

ok

Guess you like

Origin www.cnblogs.com/gbq-dog/p/10991662.html