首先token认证环境搭建:
安装模块:pip install djangorestframework
在settings中添加参数:
如图:
继续添加REST_FRAMEWORK项:
如图:
配置如下:
REST_FRAMEWORK = { # 权限验证,全局配置 "DEFAULT_PERMISSION_CLASSES":( 'rest_framework.permissions.AllowAny', # 允许所有用户 # 'rest_framework.permissions.IsAdminUser', # 管理员用户 # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', #'rest_framework.permissions.IsAuthenticated', ), # 身份认证 "DEFAULT_AUTHENTICATION_CLASSES":( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', # token认证 ) }
同步数据库生成authtoken_token表:
编写登录视图函数,登录成功产生token:
from django.contrib.auth import authenticate, login from rest_framework.authtoken.models import Token from rest_framework.permissions import AllowAny,IsAuthenticated from django.http import HttpResponse, JsonResponse, HttpResponseRedirect class LoginViewSet(APIView): permission_classes = (AllowAny,) #todo 登录允许每个人访问,元祖要加逗号 def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if not user: result = {"code": 1, "msg": "用户名或密码错误"} return JsonResponse(result) else: # 先删除原有token oid_token = Token.objects.filter(user=user) oid_token.delete() # 创建新的token token = Token.objects.create(user=user) result = {"code": 0, "msg": "login success!", "username": user.username, "token": token.key } return JsonResponse(result)
配置urls访问地址:
接口访问如图:
Permission权限验证:
Token,只有通过接口权限验证的才能访问:
如下:用户访问只有带上登录成功产生的token才能访问
from rest_framework.authentication import TokenAuthentication from django.http import HttpResponse, JsonResponse class CardListAPIView(APIView): '''rest_framework序列化''' authentication_classes = (TokenAuthentication,) # token认证方式 permission_classes = (IsAuthenticated,) # 登录用户才能访问这个接口 def get(self, request, format=None): cards = Card.objects.all() serializer = CardAPISerializer(cards, many=True) result = { "code": 0, "msg": "success!", "data": serializer.data } return Response(result) def post(self, request, format=None): '''反序列化''' verify_data = CardAPISerializer(data=request.data) if verify_data.is_valid(): # 如果数据是合法,就报存 verify_data.save() result = { "code": 0, "msg": "success!", "data": request.data } return Response(result)
配置访问地址:
接口带上token访问如图:
接口没带token,访问报错401:
设置接口权限为管理员用户才能访问,普通用户访问接口报错403:
总结:
401和403的区别:
401是登录认证失败,返回401
403是权限验证失败,返回403
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:django:token认证,以及http401和http403的区别 - Python技术站