JWT resolve

JWT resolve

jwt: Json web token, are generally used to provide delivery room and service providers authenticated user identity information in the identity, in order to obtain resources from the server, you can also add some additional business logic other necessary information statement the token can also be directly used for authentication may be encrypted.

Traditional session authentication

http is a stateless protocol, short connection agreement, and this means that if the user provides a user name and password for user authentication to the application, then the next time request, the user should once again be the job for user authentication, because according to the http protocol, we can not know which user request is sent, so in order to be able to identify the application to which the request is issued by the user, we can only store a copy of the server login users, namely session.

The login session passed in response to the browser, stored in a cookie, so that the next request to carry session , so you can identify which user requests from, and this is the traditional session-based authentication.

Session-based authentication problems exposed

  1. After each user authentication, you need to save a session, if it is stored in memory, and with the increase of the authenticated user, server spending will be significantly increased.
  2. Scalability: If the authentication records are stored in memory, then this means that next time the user requests also have to request resources on this server, so as to get the authorization, so that the distributed application, the corresponding limit the ability to load balancer. This also means that limits the scalability of applications.
  3. CSRF: cookie if intercepted, the user could be vulnerable to cross-site request forgery attacks.

Token-based authentication

It does not require the server to retain the user's authentication information or session information. This means that applications based on token authentication mechanism does not need to consider the user logged in, in which servers which have scalability, security.

Process:

  • User for username and password to the server request
  • Server to verify the user's information
  • The server sends to the user by verifying a token
  • Client storage token, this token value and carries at each request
  • The server authentication token, and returns the data

token must be passed with each request to the server, it should be kept in a request in advance, in addition, the server to support the CORS(跨来源资源共享)strategy, we usually do it on the server side Access-Control-Allow-Origin: *.

JWT:

jwt format

JWT is composed of three pieces of information, these three pieces of information with a text link together constitute Jwt string.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

structure:

header: {'typ':'JWT',"alg":'HS256'}
payload: {"user_id":1, 'username':'xx', 'exp':'超时时间'}
signature: 前两部分加密后拼接,在加密
  1. Head header : { 'Typ': 'the JWT', "ALG": 'HS256'}

    • Declared type, jet
    • Statement algorithm, the number of lines 256

    The head is then encrypted for base64ulr, constituting the first portion

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
  2. Load payload : { "user_id":. 1, 'username': 'XX', 'exp': 'timeout'} some valid information stored, sensitive information is not recommended.

    • Standard registration statement (not mandatory):

      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

      General information about the user to add the necessary information or other business needs.

    This part will be encrypted base64url, constituting a second part, for example:

    eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
  3. Signature Signature :

    This part of the string will give the two section above encrypted with .stitching, and then to be encrypted hs256, salt, then base64url for encryption, the third part, for example:

    TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
  4. Then on the upper portion with the .connection, the composition of the final token.

When the user authentication is successful, it will give the browser returns a token string, the server does not save, next time request, it will carry token

  • Timeout advanced verification (ExpriredSignature)
  • legality verification token (Comparative partially encrypted by the first two)

advantage:

  • token saved only at the front end, back end is only responsible for verification.
  • Integrates a timeout, the timeout check whether the rear end can be based on time.
  • Due to internal encryption hs256, it can not be modified token, as long as a modification authentication fails.
  • No need to store session information in the server, so it is easy to extend applications.

Disadvantages:

  • After the token issued can not be manually expired.

jwt in use in drf

installation

pip3 install djangorestframework-jwt

setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework',
    'rest_framework_jwt'    # 注册
]

# JWT过期时间设置
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(minutes=10),     # 10分钟过期
}

User login

import uuid
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from rest_framework import status
from rest_framework_jwt.settings import api_settings

from api import models

class LoginView(APIView):
    """
    登录接口
    """
    def post(self,request,*args,**kwargs):

        # 基于jwt的认证
        # 1.去数据库获取用户信息

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        user = models.UserInfo.objects.filter(**request.data).first()
        if not user:
            return Response({'code':1000,'error':'用户名或密码错误'})

        payload = jwt_payload_handler(user) # 产生第二段的字典类型{'user_id':1, 'username':xxx, 'exp':当前时间+过期时间段}
        token = jwt_encode_handler(payload) # 加密生成jwt的token(加密、拼接全做)
        return Response({'code':1001,'data':token})

User Authentication

from rest_framework.views import APIView
from rest_framework.response import Response

# from rest_framework.throttling import AnonRateThrottle,BaseThrottle

import jwt
from rest_framework import exceptions
from rest_framework_jwt.settings import api_settings


class ArticleView(APIView):
    # throttle_classes = [AnonRateThrottle,]

    def get(self,request,*args,**kwargs):
        # 获取用户提交的token,进行一步一步校验

        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER

        jwt_value = request.query_params.get('token')
        try:
            payload = jwt_decode_handler(jwt_value) # 校验
        except jwt.ExpiredSignature:
            msg = '签名已过期'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = '认证失败'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenpythonticationFailed()
        print(payload)  # 检验后的第二段数据

      return Response('文章列表')

Guess you like

Origin www.cnblogs.com/yzm1017/p/11963336.html
jwt