修改上面的项目,在urls.py文件中添加一条路由记录
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/',views.UsersView.as_view()), url(r'^auth/',views.AuthView.as_view()), ]修改视图函数
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions from django.http import JsonResponse def gen_token(username): """ 利用时间和用户名生成用户token :param username: :return: """ import time import hashlib ctime=str(time.time()) hash=hashlib.md5(username.encode("utf-8")) hash.update(ctime.encode("utf-8")) return hash.hexdigest() class AuthView(APIView): def post(self, request, *args, **kwargs): """ 获取用户提交的用户名和密码,如果用户名和密码正确,则生成token,并返回给用户 :param request: :param args: :param kwargs: :return: """ res = {'code': 1000, 'msg': None} user = request.data.get("user") pwd = request.data.get("pwd") from app01 import models user_obj = models.UserInfo.objects.filter(user=user, pwd=pwd).first() if user_obj: token = gen_token(user) # 生成用户口令 # 如果数据库中存在口令则更新,如果数据库中不存在口令则创建用户口令 models.Token.objects.update_or_create(user=user_obj, defaults={'token': token}) print("user_token:", token) res['code'] = 1001 res['token'] = token else: res['msg'] = "用户名或密码错误" return JsonResponse(res) class UserAuthView(BaseAuthentication): def authenticate(self,request): tk=request.query_params.GET.get("tk") # 获取请求头中的用户token from app01 import models token_obj=models.Token.objects.filter(token=tk).first() if token_obj: # 用户数据库中已经存在用户口令返回认证元组 return (token_obj.user,token_obj) raise exceptions.AuthenticationFailed("认证失败") def authenticate_header(self,request): pass class UsersView(APIView): authentication_classes = [UserAuthView,] def get(self,request,*args,**kwargs): return HttpResponse(".....")创建用户数据库的类
from django.db import models class UserInfo(models.Model): user=models.CharField(max_length=32) pwd=models.CharField(max_length=64) email=models.CharField(max_length=64) class Token(models.Model): user=models.OneToOneField(UserInfo) token=models.CharField(max_length=64)创建数据库,并添加两条用户记录
再创建一个test_client.py文件,来发送post请求
import requests response=requests.post( url="http://127.0.0.1:8000/auth/", data={'user':'user1','pwd':'user123'}, ) print("response_text:",response.text)启动Django项目,运行test_client.py文件,则项目的响应信息为
response_text: {"code": 1001, "msg": null, "token": "eccd2d256f44cb25b58ba602fe7eb42d"}由此,就完成了自定义的基于token的用户认证
如果想在项目中使用自定义的认证方式时,可以在authentication_classes继承刚才的认证的类即可
authentication_classes = [UserAuthView,APIViiew]