【django后端分離】Django Rest Framework之認證系統之redis數據庫的token認證(token過期時間)


1:登錄視圖

redis_cli.py文件:
          import redis
          Pool= redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)

登錄視圖文件:
import redis
from utils.redis_cli import Pool    # 創建redis連接池


class
UserLogin(APIView): """ 用戶登陸認證: 登錄成功更新token值,並且返回給前端,登錄失敗拋出異常提示 """ authentication_classes = [] # 登錄接口不需要token認證 def post(self, request, *args, **kwargs): username = str(request.data.get("username")) # 前端需要提交json格式 password = str(request.data.get("password")) try: csrf = {} user_obj = models.UserInfo.objects.filter(username=username,password=password).first() if not user_obj: csrf['code'] = 401 csrf['message'] = "賬號或者密碼錯誤" return JsonResponse(csrf) t = datamd5.md5(username) # md5給token加密 token = t + ":" + username # token:username 加上用戶名標識, sr = redis.Redis(connection_pool=Pool) sr.hset(username,"token",token) # 存入格式 sr.expire(username,10800) # 3個小時過期 csrf['token'] = token return JsonResponse(csrf)

2:認證系統文件配置(token認證)

from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication #繼承認證類


class Authtication(BaseAuthentication):
    def authenticate(self, request):
        try:
            request_token = request.META.get('HTTP_AUTHENTICATE',"")
            print("request_token",request_token)
            token,username = request_token.split(":")      # 登錄視圖設置的token有 :符號
            sr = redis.Redis(connection_pool=Pool)
        except Exception as e:
            raise exceptions.AuthenticationFailed({"code": 405, "error": "請求錯誤,請重新登錄"})

            # 判斷登錄是否有token
            if not token:
                raise exceptions.AuthenticationFailed({"code": 407,"error":"用戶請求異常,未攜帶token"})

            # 判斷 token 正確或者是否過期
            redis_token = sr.hget(username,"token")
            if request_token != redis_token:
                raise exceptions.AuthenticationFailed({"code": 405, "error": "請求錯誤,請重新登錄"})



    def authenticate_header(self, request):
        pass

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM