用户模块--登录及权限认证

使用 DRF 框架 再带的登陆认证进行登陆

userapp.urls.py

from django.urls import path
from userapp import views as userviews
from rest_framework_jwt.views import obtain_jwt_token   # drf自带的登陆认证,会自动生成jwt-token

urlpatterns = [
    path('login/', obtain_jwt_token),   # 登录
]

userapp.views.py 中自定义 登陆后返回的数据(函数名可自定义)

def jwt_response_payload_handler(token, user=None, request=None):
    """
        :param token: jwt生成的token值
        :param user: User对象
        :param request: 请求
    """
    return {  # 根据自己需求返回数据
        'token': token,
        'name': user.nick_name,
        "username": user.username,
        # "authenticated": True,
        # "role": None,
        'id': user.id,
        # "email": user.email
    }

在setting.py 中告诉django使用我们定义的返回数据

import datetime

JWT_AUTH = {
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    'JWT_RESPONSE_PAYLOAD_HANDLER':
       'userapp.views.jwt_response_payload_handler',  # 重新login登录返回函数
}

drf自带的权限认证

settings.py中指定验证方式

REST_FRAMEWORK = {
    # 指定验证方式
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}
  • 全局配置
REST_FRAMEWORK = {
    # 认证、权限,全局配置
    'DEFAULT_PERMISSION_CLASSER': (
        'rest_framework.permissions.IsAuthenticated',  # IsAuthenticated 只有登陆后携带token的用户才能访问
        # 'rest_framework.permissions.IsAdminUser ',  # IsAdminUser 只有超级用户才能访问
        # 'rest_framework.permissions.AllowAny ',  # AllowAny 允许所有人访问		
    )
}

views.py

class Test(APIView):
    permission_classes = [IsAuthenticated]
	# IsAuthenticated 只有登陆后携带token的用户才能访问
	# IsAdminUser 只有超级用户才能访问
	# AllowAny 允许所有人访问
    def get(self, request):
        return Response({'msg': 'OK'})
  • 局部配置
    views.py 中类中指定认证方式
from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
class Test(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        return Response({'msg': 'OK'})

自定义权限认证

userapp.permission.py中定义自己的认证方法(继承BasePermission)

from rest_framework.permissions import BasePermission
from userapp.models import User


class VIPPermission(BasePermission):
    message = '必须是VIP才能访问'

    def has_permission(self, request, view):
        print(request.user.id)
        user_obj = User.objects.filter(id=request.user.id).first()
        if user_obj.vip_id != 1:
            return False
        return True
  • 局部配置
    views.py
from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response
from userapp.permission import VIPPermission
class Test(APIView):
    permission_classes = [VIPPermission]
    def get(self, request):
        return Response({'msg': 'OK'})
  • 全局配置
    settings.py
REST_FRAMEWORK = {
    # 认证、权限,全局配置
    'DEFAULT_PERMISSION_CLASSER': (
        'userapp.permission.VIPPermission'
    )
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值