django--JWT认证

JWT认证

JWT简介

JWT全称为Json Web Token, 是由三部分进行组成:

  • base64(头部).base(载荷).hash256(base64(头部).base(载荷).密钥)
    • base64是可逆算法, 而hash256是不可逆算法
    • 密钥是存储在服务器的固定字符串

安装

pip install djangorestframework-jwt

djang-jwt开发

配置

# settings.py

import datetime

JWT_AUTH = {
    # 过期时间
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}

手动签发jwt token

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)

基于django_restframework-jwt的全局认证

import jwt
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt import authentication

class JSONWebTokenAuthentication(authentication.BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_value = authentication.get_authorization_header(request)

        if not jwt_value:
            raise AuthenticationFailed('Authorization 字段是必须的')
        try:
            payload = authentication.jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('签名过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('非法用户')
        user = self.authenticate_credentials(payload)

        return user, jwt_value

全局启用

# settings.py

REST_FRAMEWORK = {
    # 认证模块
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'user.authentications.JSONWebTokenAuthentication',
    ),
}

局部启用禁用:任何一个cbv类首行

# 局部禁用
authentication_classes = []

# 局部启用
from user.authentications import JSONWebTokenAuthentication
authentication_classes = [JSONWebTokenAuthentication]
posted @ 2019-09-15 17:42  蔚蓝的爱  阅读(266)  评论(0编辑  收藏  举报