当前位置:   article > 正文

Django restframework auth 认证_django-rest-framework auth

django-rest-framework auth

在页面渲染和权限判断之前,判断用户是否可以访问该页面,身份验证是将传入请求与一组识别凭证(例如请求的用户或其签名的令牌)相关联的机制。然后,权限和限制策略可以使用这些凭据来确定请求是否应该被允许。

如何确定身份认证

身份验证方案的定义为“类列表”,即如果您需要定义身份认证的方案,需要编写验证类(通过继承Base类)。REST框架将尝试对列表中的每个类进行身份验证,并将设置request.userrequest.auth使用成功进行身份验证的第一个类的返回值(在编写过程中有可能编写了多个验证类,程序将一个类一个类进行匹配,程序将返回第一个匹配正确的值)。如果没有任何类通过身份验证,request.user则将设置为的实例django.contrib.auth.models.AnonymousUser,并将request.auth设置为None

未认证请求的request.user和值request.auth可以使用UNAUTHENTICATED_USERUNAUTHENTICATED_TOKEN设置进行修改。

在django restframework中,有四个已经提供好的,可以直接使用的认证类,BasicAuthentication && TokenAuthentication && SessionAuthenticatoin && RemoteUserAuthentication

BasicAuthentication:第一个样例

step1:DEFAULT_AUTHENTICATION_CLASSES设置全局设置默认身份验证方案,例如:

  1. #settings.py
  2. REST_FRAMEWORK = {
  3. 'DEFAULT_AUTHENTICATION_CLASSES': [
  4. 'rest_framework.authentication.BasicAuthentication',
  5. ]
  6. }

step2:在Views文件中使用身份验证方案(并编号URL文件)

  1. # url.py
  2. from django.contrib import admin
  3. from django.urls import path
  4. from django.conf.urls import url
  5. from pert.views import Example
  6. urlpatterns = [
  7. path('admin/', admin.site.urls),
  8. path('example/', Example.as_view()),
  9. ]
  10. # views.py
  11. from rest_framework.authentication import SessionAuthentication, BasicAuthentication
  12. from rest_framework.permissions import IsAuthenticated
  13. from rest_framework.response import Response
  14. from rest_framework.views import APIView
  15. class ExampleView(APIView):
  16. # 由于在step1中设置了全局的验证方案,如果在编程过程中不需要使用全局验证方案则
  17. # authentication_classes = []
  18. authentication_classes = [BasicAuthentication]
  19. #设置,通过认证的用户具有访问权限
  20. permission_classes = [IsAuthenticated]
  21. def get(self, request, format=None):
  22. content = {
  23. 'user': unicode(request.user), # `django.contrib.auth.User` instance.
  24. 'auth': unicode(request.auth), # None
  25. }
  26. return Response(content)

step3:验证,当你get访问页面example时,您会发现跳出一个输入框【输入username && password】,(即匹配 默认的auth_user  MODEL )

自定义认证:第二个样例

step1:APP目录下生成utils目录,utils目录下生成authenticate.py文件,并编写认证类代码:

To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method.

Typically the approach you should take is:

  • If authentication is not attempted, return None. Any other authentication schemes also in use will still be checked.
  • If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.

You may also override the .authenticate_header(self, request) method. If implemented, it should return a string that will be used as the value of the WWW-Authenticate header in a HTTP 401 Unauthorized response.

If the .authenticate_header() method is not overridden, the authentication scheme will return HTTP 403 Forbidden responses when an unauthenticated request is denied access.

  1. # APPname.utils.authenticate
  2. from pert import models
  3. from rest_framework import exceptions
  4. from rest_framework.authentication import BaseAuthentication
  5. class MyAuthenticate(BaseAuthentication):
  6. def authenticate(self, request):
  7. token = request._request.GET.get('token') # 获取token参数
  8. token_obj = models.UserToken.objects.filter(token=token).first() # 在数据库UserToken查找是否有相应的对象
  9. if not token_obj: # 如果没有,则报错
  10. raise exceptions.AuthenticationFailed('用户认证失败')
  11. return (token_obj.user, token_obj) # 这里需要返回两个对象,分别是UserInfo对象和UserToken对象
  12. def authenticate_header(self, request): # 返回相应头信息
  13. pass

step2:DEFAULT_AUTHENTICATION_CLASSES设置全局设置默认身份验证方案,例如:

  1. #settings.py
  2. REST_FRAMEWORK = {
  3. 'DEFAULT_AUTHENTICATION_CLASSES': [
  4. 'rest_framework.authentication.BasicAuthentication',
  5. 'rest_framework.authentication.SessionAuthentication',
  6. 'appname.utils.authenticate.MyAuthenticate',
  7. ]
  8. }

 step3:在Views文件中使用身份验证方案(并编号URL文件)

  1. # url.py
  2. from django.contrib import admin
  3. from django.urls import path
  4. from django.conf.urls import url
  5. from pert.views import Example
  6. urlpatterns = [
  7. path('admin/', admin.site.urls),
  8. path('api/v1/auth/', AuthView.as_view()),
  9. path('api/v1/order/', OrderView.as_view())
  10. ]
  11. #models
  12. from django.db import models
  13. class UserInfo(models.Model):
  14. USER_TYPE = (
  15. (1, '普通用户'),
  16. (2, 'VIP'),
  17. (3, 'SVIP')
  18. )
  19. user_type = models.IntegerField(choices=USER_TYPE, default=1)
  20. username = models.CharField(max_length=32)
  21. password = models.CharField(max_length=64)
  22. class UserToken(models.Model):
  23. user = models.OneToOneField(UserInfo,on_delete=models.CASCADE)
  24. token = models.CharField(max_length=64)
  25. # views.py
  26. class AuthView(View):
  27. def get(self, request, *args, **kwargs):
  28. # request.session["user"] = "szy"
  29. ret = {'code': 1000, 'msg': 'success', 'name': 'get method'}
  30. ret = json.dumps(ret, ensure_ascii=False)
  31. return HttpResponse(ret)
  32. def post(self, request, *args, **kwargs):
  33. ret = {'code': 1000, 'msg': None}
  34. try:
  35. data = JSONParser().parse(request)
  36. print(data)
  37. user = data["username"]
  38. print(user)
  39. pwd = data["password"]
  40. print(pwd)
  41. obj = models.UserInfo.objects.filter(username=user).first()
  42. if not obj:
  43. obj = models.UserInfo.objects.create(username=user, password=pwd)
  44. ret['code'] = 1001
  45. ret['msg'] = '创建用户成功'
  46. # 为用户创建token
  47. token = md5(user)
  48. # 存在就更新,不存在就创建
  49. models.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
  50. ret['token'] = token
  51. except Exception as e:
  52. ret['code'] = 1002
  53. ret['msg'] = '请求异常'
  54. return JsonResponse(ret)
  55. class OrderView(APIView):
  56. authentication_classes = [MyAuthenticate]
  57. # permission_classes = [IsAuthenticated]
  58. def get(self, request, *args, **kwargs):
  59. print(str(request.user))
  60. ret = {
  61. 'code': 1024,
  62. 'msg': '订单获取成功',
  63. }
  64. try:
  65. ret['data'] = ORDER_DICT
  66. except Exception as e:
  67. pass
  68. return JsonResponse(ret)

 step4:验证

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

闽ICP备14008679号