目錄python
JWT全稱爲Json Web Token, 是由三部分進行組成:算法
pip install djangorestframework-jwt
django
# settings.py import datetime JWT_AUTH = { # 過時時間 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), }
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)
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', ), }
# 局部禁用 authentication_classes = [] # 局部啓用 from user.authentications import JSONWebTokenAuthentication authentication_classes = [JSONWebTokenAuthentication]