1.下載JWT
pip install djangorestframework-jwt
2.簽發token
#導入jwt
from rest_framework_jwt.serializers import jwt_payload_handler from rest_framework_jwt.serializers import jwt_encode_handler
#導入jwt默認的登錄模塊 from django.contrib import auth class LoginAPIView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') if not (username and password): return Response({ 'error': 'username與password為必須字段' }) user_obj = auth.authenticate(username=username, is_active=True, password=password) if user_obj: # 簽發token payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) return Response({ 'status': 0, 'msg': 'ok', 'token': token }) else: return Response({ 'status': 1, 'msg': 'username與password有誤' })
3.全局配置jwt和局部配置
# 全局認證組件 REST_FRAMEWORK={ 'DEFAULT_AUTHENTICATION_CLASSES':[ 'app01.cache_jwt.JwtToken', ] }
#設置token過期時間
import datetime
JWT_AUTH = {
# 過期時間
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
}
#局部使用jwt authentication_classes = [JwtToken] #局部禁用jwt authentication_classes = []
4.jwt的驗證
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication from rest_framework_jwt.authentication import jwt_decode_handler from rest_framework import exceptions class JwtToken(BaseJSONWebTokenAuthentication): def authenticate(self, request): jwt_value = request.META.get('HTTP_TOKEN') if not jwt_value: raise exceptions.AuthenticationFailed('token 字段是必須的') try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: raise exceptions.AuthenticationFailed('token已過期') except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed('token非法') user = self.authenticate_credentials(payload) return (user, jwt_value)
注釋:嚴格的token驗證是要在簽發的時候存進數據庫或者緩存中,然后在前端向后端發送數據的時候從數據庫中或者緩存中取出來進行校驗
