""" 1) 服務器不要存儲token,token交給每個客戶端本身存儲,服務器壓力小 2)服務器存儲的是 簽發和校驗token 兩段算法,簽發認證的效率高 3)算法完成各集羣服務器同步成本低,路由項目完成集羣部署(適應高併發) """
""" 1) jwt token採用三段式:頭部.載荷.簽名 2)每一部分都是一個json字典加密形參的字符串 3)頭部和載荷採用的是base64可逆加密(前臺後臺均可以解密) 4)簽名採用hash256不可逆加密(後臺校驗採用碰撞校驗) 5)各部分字典的內容: 頭部:基礎信息 - 公司信息、項目組信息、可逆加密採用的算法 載荷:有用但非私密的信息 - 用戶可公開信息、過時時間 簽名:頭部+載荷+祕鑰 不可逆加密後的結果 注:服務器jwt簽名加密祕鑰必定不能泄露 簽發token:固定的頭部信息加密.當前的登錄用戶與過時時間加密.頭部+載荷+祕鑰生成不可逆加密 校驗token:頭部可校驗也能夠不校驗,載荷校驗出用戶與過時時間,頭部+載荷+祕鑰完成碰撞檢測校驗token是否被篡改 """
https://github.com/jpadilla/django-rest-framework-jwt
>: pip3 install djangorestframework-jwt
# ObtainJSONWebToken視圖類就是經過username和password獲得user對象而後簽發token from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token urlpatterns = [ # url(r'^jogin/$', ObtainJSONWebToken.as_view()), url(r'^jogin/$', obtain_jwt_token), ]
from rest_framework.views import APIView from utils.response import APIResponse # 必須登陸後才能訪問 - 經過了認證權限組件 from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication class UserDetail(APIView): authentication_classes = [JSONWebTokenAuthentication] # jwt-token校驗request.user permission_classes = [IsAuthenticated] # 結合權限組件篩選掉遊客 def get(self, request, *args, **kwargs): return APIResponse(results={'username': request.user.username})
# 路由 url(r'^user/detail/$', views.UserDetail.as_view()), # 接口:/api/user/detail/ # 認證信息:必須在請求頭的 Authorization 中攜帶 "jwt 後臺簽發的token" 格式的認證字符串
# 前提:給一個局部禁用了全部 認證與權限 的視圖類發送用戶信息獲得token,其實就是登陸接口 # 1)rest_framework_jwt.views.ObtainJSONWebToken 的 父類 JSONWebTokenAPIView 的 post 方法 # 接受有username、password的post請求 # 2)post方法將請求數據交給 rest_framework_jwt.serializer.JSONWebTokenSerializer 處理 # 完成數據的校驗,會走序列化類的 全局鉤子校驗規則,校驗獲得登陸用戶並簽發token存儲在序列化對象中
def validate(self, attrs): # 帳號密碼字典 credentials = { self.username_field: attrs.get(self.username_field), 'password': attrs.get('password') } if all(credentials.values()): # 簽發token第1步:用帳號密碼獲得user對象 user = authenticate(**credentials) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) # 簽發token第2步:經過user獲得payload,payload包含着用戶信息與過時時間 payload = jwt_payload_handler(user) # 在視圖類中,能夠經過 序列化對象.object.get('user'或者'token') 拿到user和token return { # 簽發token第3步:經過payload簽發出token 'token': jwt_encode_handler(payload), 'user': user } else: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "{username_field}" and "password".') msg = msg.format(username_field=self.username_field) raise serializers.ValidationError(msg)
# 1)經過username、password獲得user對象 # 2)經過user對象生成payload:jwt_payload_handler(user) => payload # from rest_framework_jwt.serializers import jwt_payload_handler # 3)經過payload簽發token:jwt_encode_handler(payload) => token # from rest_framework_jwt.serializers import jwt_encode_handler
# 前提:訪問一個配置了jwt認證規則的視圖類,就須要提交認證字符串token,在認證類中完成token的校驗 # 1)rest_framework_jwt.authentication.JSONWebTokenAuthentication 的 父類 BaseJSONWebTokenAuthentication 的 authenticate 方法 # 請求頭拿認證信息jwt-token => 經過反爬小規則肯定有用的token => payload => user
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ # 帶有反爬小規則的獲取token:前臺必須按 "jwt token字符串" 方式提交 # 校驗user第1步:從請求頭 HTTP_AUTHORIZATION 中拿token,並提取 jwt_value = self.get_jwt_value(request) # 遊客 if jwt_value is None: return None # 校驗 try: # 校驗user第2步:token => payload payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() # 校驗user第3步:token => payload user = self.authenticate_credentials(payload) return (user, jwt_value)
# 1)從請求頭中獲取token # 2)根據token解析出payload:jwt_decode_handler(token) => payloay # from rest_framework_jwt.authentication import jwt_decode_handler # 3)根據payload解析出user:self.authenticate_credentials(payload) => user # 繼承drf-jwt的BaseJSONWebTokenAuthentication,拿到父級的authenticate_credentials方法
from django.db import modelsfrom django.contrib.auth.models import AbstractUserclass User(AbstractUser): mobile = models.CharField(max_length=11, unique=True) class Meta: db_table = 'api_user' verbose_name = '用戶表' verbose_name_plural = verbose_name def __str__(self): return self.username
from rest_framework import serializers from . import models import re # 拿到前臺token的兩個函數: user => payload => 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 from rest_framework_jwt.serializers import jwt_payload_handler from rest_framework_jwt.serializers import jwt_encode_handler # 1) 前臺提交多種登陸信息都採用一個key,因此後臺能夠自定義反序列化字段進行對應 # 2) 序列化類要處理序列化與反序列化,要在fields中設置model綁定的Model類全部使用到的字段 # 3) 區分序列化字段與反序列化字段 read_only | write_only # 4) 在自定義校驗規則中(局部鉤子、全局鉤子)校驗數據是否合法、肯定登陸的用戶、根據用戶簽發token # 5) 將登陸的用戶與簽發的token保存在序列化類對象中 class UserModelSerializer(serializers.ModelSerializer): # 自定義反序列字段:必定要設置write_only,只參與反序列化,不會與model類字段映射 usr = serializers.CharField(write_only=True) pwd = serializers.CharField(write_only=True) class Meta: model = models.User fields = ['usr', 'pwd', 'username', 'mobile', 'email'] # 系統校驗規則 extra_kwargs = { 'username': { 'read_only': True }, 'mobile': { 'read_only': True }, 'email': { 'read_only': True }, } def validate(self, attrs): usr = attrs.get('usr') pwd = attrs.get('pwd') # 多方式登陸:各分支處理獲得該方式下對應的用戶 if re.match(r'.+@.+', usr): user_query = models.User.objects.filter(email=usr) elif re.match(r'1[3-9][0-9]{9}', usr): user_query = models.User.objects.filter(mobile=usr) else: user_query = models.User.objects.filter(username=usr) user_obj = user_query.first() # 簽發:獲得登陸用戶,簽發token並存儲在實例化對象中 if user_obj and user_obj.check_password(pwd): # 簽發token,將token存放到 實例化類對象的token 名字中 payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) # 將當前用戶與簽發的token都保存在序列化對象中 self.user = user_obj self.token = token return attrs raise serializers.ValidationError({'data': '數據有誤'})
#實現多方式登錄簽發token:帳號、手機號、郵箱等登錄 # 1) 禁用認證與權限組件 # 2) 拿到前臺登陸信息,交給序列化類 # 3) 序列化類校驗獲得登陸用戶與token存放在序列化對象中 # 4) 取出登陸用戶與token返回給前臺 import re from . import serializers, models from utils.response import APIResponse from rest_framework_jwt.serializers import jwt_payload_handler from rest_framework_jwt.serializers import jwt_encode_handler class LoginAPIView(APIView): # 1) 禁用認證與權限組件 authentication_classes = [] permission_classes = [] def post(self, request, *args, **kwargs): # 2) 拿到前臺登陸信息,交給序列化類,規則:帳號用usr傳,密碼用pwd傳 user_ser = serializers.UserModelSerializer(data=request.data) # 3) 序列化類校驗獲得登陸用戶與token存放在序列化對象中 user_ser.is_valid(raise_exception=True) # 4) 取出登陸用戶與token返回給前臺 return APIResponse(token=user_ser.token, results=serializers.UserModelSerializer(user_ser.user).data)
import jwt from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication from rest_framework_jwt.authentication import jwt_decode_handler from rest_framework.exceptions import AuthenticationFailed class JWTAuthentication(BaseJSONWebTokenAuthentication): def authenticate(self, request): jwt_token = request.META.get('HTTP_AUTHORIZATION') # 自定義校驗規則:auth token jwt token = self.parse_jwt_token(jwt_token) if token is None: return None try: # token => payload payload = jwt_decode_handler(token) except jwt.ExpiredSignature: raise AuthenticationFailed('token已過時') except: raise AuthenticationFailed('非法用戶') # payload => user user = self.authenticate_credentials(payload) return (user, token) # 自定義校驗規則:auth token jwt,auth爲前鹽,jwt爲後鹽 def parse_jwt_token(self, jwt_token): tokens = jwt_token.split() if len(tokens) != 3 or tokens[0].lower() != 'auth' or tokens[2].lower() != 'jwt': return None return tokens[1]
from rest_framework.views import APIView from utils.response import APIResponse # 必須登陸後才能訪問 - 經過了認證權限組件 from rest_framework.permissions import IsAuthenticated # 自定義jwt校驗規則 from .authentications import JWTAuthentication class UserDetail(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): return APIResponse(results={'username': request.user.username})