当前位置:   article > 正文

权限认证[还是有问题]_明已经配置了permission_classes = (),但是如果请求不小心携带了token,会报

明已经配置了permission_classes = (),但是如果请求不小心携带了token,会报出错误

认证:

def的request对象 上便有两个属性,一个是request.user,一个是request.auth,前者就是django中User对象,后者根据不同认证机制有不同的对象

rest_framework.authentication.BasicAuthentication

基本的授权,每次都要在Header中把用户名和密码传给服务器,因此不是很安全,不能在生产环境中使用

rest_framework.authentication.SessionAuthentication

基于 django的session机制实现,如果前端部分是网页,那么用他是可以的,如果前端是ios或安卓,用它就不太方便

rest_framework.authentication.TokenAuthentication

基于token的认证机制,只要登陆完成便会返回一个token,以后请求一些需要登陆的api,就通过传递这个token就可以了,并且这个token是存储服务器的数据库中的,但是这种token的方式有一个缺点,就是他没有自动过期机制

JSON Web Token 认证机制:

json web token 简称 jwt 推荐使用 jwt 是在成功后,把用户的相关信息(比如用户id)以及过期时间进行加密,然后生成一个token返回给客户端,客户端拿到后可以存储起来,以后每次请求的时候都携带这个token,服务器在接收需要登陆api请求,这个token进行解密,然后获取过期时间和用户信息,如果过期了或者用户信息不对,那么都是认证失败

  1. # -*- coding: utf-8 -*-
  2. from rest_framework import viewsets
  3. from meituan.models import Merchant
  4. from .serializers import MerchantSerializer
  5. from rest_framework.authentication import BasicAuthentication
  6. from rest_framework.permissions import IsAuthenticated
  7. class MerchantViewSet(viewsets.ModelViewSet):
  8. queryset = Merchant.objects.all()
  9. serializer_class = MerchantSerializer
  10. # 用来验证用户是否已经成功登陆
  11. authentication_classes = [BasicAuthentication]
  12. # 权限 经过授权才能访问
  13. permission_classes = [IsAuthenticated]

没有授权

 

Django 创建超级用户

 

 

 

 手动实现JWT认证

pip install pyjwt

  1. import jwt
  2. import time
  3. from django.conf import settings
  4. def generate_jwt(user):
  5. # 设置过期时间
  6. timestamp = int(time.time()) + 60*60*24*7
  7. # 因为jwt.encode 返回的是bytes 数据类型,因此需要decode解码成str类型
  8. return jwt.encode({"userid":user.pk,"exp":timestamp},settings.SECRET_KEY).encode('utf-8')
  1. from .authentications import generate_jwt
  2. from django.contrib.auth import get_user_model
  3. from rest_framework.response import Response
  4. from rest_framework.decorators import api_view
  5. User = get_user_model()
  6. # 模拟登陆
  7. @api_view(['GET'])
  8. def token_view(request):
  9. token = generate_jwt(User.objects.first())
  10. return Response({"token":token})

 jwt eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOjEsImV4cCI6MTY2Mzc2ODAwMS4zNzgwODQyfQ._ktzqs2_FYSGmpZ4FZjdzTMr4BjD_IxLVKpPtyf03jQ

  1. # -*- coding: utf-8 -*-
  2. import jwt
  3. import time
  4. from django.conf import settings
  5. from rest_framework.authentication import BaseAuthentication,get_authorization_header
  6. from rest_framework import exceptions
  7. from django.contrib.auth import get_user_model
  8. User = get_user_model()
  9. def generate_jwt(user):
  10. # 设置过期时间
  11. timestamp = int(time.time()) + 60*60*24*7
  12. # 因为jwt.encode 返回的是bytes 数据类型,因此需要decode解码成str类型
  13. return jwt.encode({"userid":user.pk,"exp":timestamp},settings.SECRET_KEY).decode('utf-8')
  14. class JWTAuthentication(BaseAuthentication):
  15. """
  16. Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
  17. """
  18. keyword = 'jwt'
  19. model = None
  20. def authenticate(self, request):
  21. auth = get_authorization_header(request).split()
  22. if not auth or auth[0].lower() != self.keyword.lower().encode():
  23. return None
  24. if len(auth) == 1:
  25. msg = 'Authorization 不可用!'
  26. raise exceptions.AuthenticationFailed(msg)
  27. elif len(auth) > 2:
  28. msg = 'Authorization 不可用! 应该提供一个空格!'
  29. raise exceptions.AuthenticationFailed(msg)
  30. try:
  31. jwt_token = auth[1]
  32. jwt_info = jwt.decode(jwt_token,settings.SECRET_KEY)
  33. userid = jwt_info.get('userid')
  34. try:
  35. user = User.objects.get(pk=userid)
  36. return (user,jwt_token)
  37. except:
  38. msg = "用户不存在!"
  39. raise exceptions.AuthenticationFailed(msg)
  40. except UnicodeError:
  41. msg = "token 已经过期了!"
  42. raise exceptions.AuthenticationFailed(msg)

 

 

 

  1. # -*- coding: utf-8 -*-
  2. from rest_framework import viewsets
  3. from meituan.models import Merchant
  4. from .serializers import MerchantSerializer
  5. from rest_framework.authentication import BasicAuthentication
  6. from rest_framework.permissions import IsAuthenticated,AllowAny,IsAdminUser
  7. from .authentications import generate_jwt,JWTAuthentication
  8. from django.contrib.auth import get_user_model
  9. from rest_framework.response import Response
  10. from rest_framework.decorators import api_view
  11. User = get_user_model()
  12. class MerchantViewSet(viewsets.ModelViewSet):
  13. queryset = Merchant.objects.all()
  14. serializer_class = MerchantSerializer
  15. # 用来验证用户是否已经成功登陆
  16. authentication_classes = [JWTAuthentication,BasicAuthentication]
  17. # 权限 经过授权才能访问
  18. permission_classes = [IsAuthenticated,IsAdminUser]
  19. # AUTHORIZATION
  20. # basic username:password
  21. # 模拟登陆
  22. @api_view(['GET'])
  23. def token_view(request):
  24. token = generate_jwt(User.objects.first())
  25. return Response({"token":token})

 jwt decode error is It is required that you pass in a value for the “algorithms“ argument when calli

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/71634
推荐阅读
相关标签
  

闽ICP备14008679号