• DRF登录认证组件


    DRF登录认证组件

    1.写一个登录认证类(类名随意,类中的方法名固定)

    from app01 import models
    from rest_framework import exceptions
    from rest_framework.authentication import BaseAuthentication
    
    
    class Auth(BaseAuthentication):
    
        def authenticate(self,request):
            token = request.query_params.get('token')
            res = models.Token.objects.filter(token=token).first()
            if res:
                #放回的res.user就是将user添加到request中user中,res会添加到request的auth中
                return res.user,res
            else:
                raise exceptions.APIException('您还没有登录!')
    

    2.全局使用

    ​ 在setting中配置

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': ['app01.AuthAPI.Auth']
    }
    

    ​ 每次走视图行数之前都会先走认证类

    3.局部禁用(在视图类中添加)

    authentication_classes = [ ]
    

    例如:

    ​ 这样Login视图类就不会使用Auth认证

    class Login(APIView):
        authentication_classes = [ ]
        def post(self,request):
            user = models.User.objects.filter(name=request.data.get('name'),pwd=request.data.get('pwd')).first()
            if not user:
                return JsonResponse({'msg':'用户名或者密码错误!'})
            else:
                token = uuid.uuid4()
                models.Token.objects.update_or_create(user=user,defaults={'token':token})
                return JsonResponse({'msg':'登录成功!','token':token})
    

    4.局部使用

    ​ 如果要实现局部使用就不能在setting中配置了,

    ​ 在要使用的视图类中添加如下字段

    authentication_classes = [Auth, ]
    

    ​ 例如:

    class Login(APIView):
        authentication_classes = [Auth, ]
        def post(self,request):
            user = models.User.objects.filter(name=request.data.get('name'),pwd=request.data.get('pwd')).first()
            if not user:
                return JsonResponse({'msg':'用户名或者密码错误!'})
            else:
                token = uuid.uuid4()
                models.Token.objects.update_or_create(user=user,defaults={'token':token})
                return JsonResponse({'msg':'登录成功!','token':token})
    
  • 相关阅读:
    JSP实现页面自动跳转
    marquee属性的使用说明
    jsp 按钮 超链接 直接跳转至另一页面
    生成验证码图片代码
    js 通过判断月数填充日数下拉框
    邮箱正则验证
    jsp 验证用正则表达式
    onselectstart 与 -moz-user-select
    onselectstart 、onselect区别
    NSOperation基本操作
  • 原文地址:https://www.cnblogs.com/jianhaozhou/p/10114842.html
Copyright © 2020-2023  润新知