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