drf-----认证组件

rf-jwt提供的身份认证类(常用)

        rf-jwt为我们提供了其已经写好的身份认证类:

      1.JSONWebTokenAuthentication 需要在请求头中加入{'Authorization':'jwt token}     

                jwt 空格 token串

  2 BasicAuthentication,基于用户名密码认证方式

      3.SessionAuthentication,基于Session认证方式

      4. TokenAuthentication,基于令牌认证方式(一个用户绑定一个令牌,每次请求在请求

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

头中加上 )

后端配置

from rest_framework_jwt.authentication import JSONWebTokenAuthentication

class UserListViewSet(ListModelMixin,GenericViewSet):
    # ---------------三大认证配置---------------我是分割线
    # authentication_classes = [authentications.MyAuthentication]
    authentication_classes = [JSONWebTokenAuthentication]

    # -----------------正常逻辑-----------------我是分割线
    queryset = models.User.objects.filter(is_active=True).all()
    serializer_class = serializers.UserModelSerializer

认证组件使用步骤(固定用法)

1 写一个类,继承BaseAuthentication
    2 在类中写:重写    authenticate
    3 在方法中,完成登录认证,如果 不是登录的,抛异常
    4 如果是登录的,返回登录用户和token
    
    5 在视图类中,使用认证类(局部使用)
    class BookView(APIView):
        authentication_classes = [LoginAuth, ] 
     
    6 全局使用:
    # 全局使用
    ### 重点:不要在配置文件中,导入莫名其妙的包

在settings.py中配置
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'app01.auth.LoginAuth'     #自定义认证类的路径

             'rest_framework.authentication.BasicAuthentication',  # username和password形式认证
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局jwt
        ],

    }
    
    7 全局使用后,局部禁用
    class UserView(ViewSet):
        # 局部禁用
        authentication_classes = []
    
    8 认证类的使用顺序
        -优先用视图类配置的
        -其次用项目配置文件
        -最后用drf默认的配置
       
# 小重点;一旦通过认证,在request中就有当前登录用户
    def get(self, request):
        # 一旦通过认证,在request中就有当前登录用户
        print(request.user.name,'访问了接口')

 登录部分代码

from rest_framework.viewsets import ViewSet
import uuid
class UserView(ViewSet):
    authentication_classes = [Actions, ]        #认证
    @action(methods=['POST'],detail=False)
    def login(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        # token=request.MITA.get('HTTP_TOKEN')
        user=models.User.objects.filter(username=username,password=password).first()
        if user:
            token=str(uuid.uuid4())
            models.UserToken.objects.update_or_create(user_id=user.id,defaults={'token':token})
            return Response({'code':100,"msg":'登陆成功','token':token})
        return Response({'code':101,"msg":'用户名或密码错误'})

  

models.UserToken.objects.update_or_create(user_id=user.id,defaults={'token':token})

user_id=user.id根据这个条件去数据库中查询,没有查询到,就根据defaults={'token':token})

重新创建,查询到了,和defaults={'token':token})不一样,就更新

 认证类

class Actions(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get('token')
        print(token)
        user_token = models.UserToken.objects.filter(token=token).first()
        if user_token:
            user=user_token.user   # 当前登录用户就是user
            return user, token
        else:
            raise AuthenticationFailed('认证不通过')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值