django--JWT認證

JWT認證

JWT簡介

JWT全稱爲Json Web Token, 是由三部分進行組成:算法

  • base64(頭部).base(載荷).hash256(base64(頭部).base(載荷).密鑰)
    • base64是可逆算法, 而hash256是不可逆算法
    • 密鑰是存儲在服務器的固定字符串

安裝

pip install djangorestframework-jwtdjango

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]
相關文章
相關標籤/搜索