auth认证组件

自定义drf配置

配置全局认证类

REST_FRAMEWORK = {
    # 全局配置 - 配置认证类
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        'api.authentication.TokenAuthentication',
    )
}

自定义认证类

# 自定义认证类
# 前后台分离项目,认证字段通常为Token

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
class TokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request._request.META.get('HTTP_TOKEN')
        if token != '123321':
            raise exceptions.NotAuthenticated('认证失败')
        return None

全局认证,局部解禁认证

 # 局部解除认证
    authentication_classes = ()

全局部认证,局部认证

from . import authentication
authentication_classes = (authentication.TokenAuthentication, )

auth认证

更换auth认证绑定的User表

app.表名

AUTH_USER_MODEL = 'api.User'

user、groups、permissions三表关系

三表连查

自定义权限类

1、setting中引入自定义的类
REST_FRAMEWORK = {

自定义认证类 - 重写authenticate - 通过(user和auth | None) 失败(raise)

'DEFAULT_AUTHENTICATION_CLASSES': [
    # 前台sessionid与后台django_session完成认证,赋值给request.user
    # 'rest_framework.authentication.SessionAuthentication',
    # 'rest_framework.authentication.BasicAuthentication',
    # 在jwt认证下,上方的认证组件可以注释
],
# 自定义权限类 - 重写has_permission - 通过(True) | 失败(False)
'DEFAULT_PERMISSION_CLASSES': [
    # 下面4个都是系统默认的权限类
    # 'rest_framework.permissions.AllowAny',(所有的都能通过)
    # 校验request.user
    # 'rest_framework.permissions.IsAuthenticated',(所有接口必须登录才能查看)
    # 查操作不校验request.user,增改删校验request.user
    # 'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    # 是否是在职用户(request.user.is_staff)
    # 'rest_framework.permissions.IsAdminUser',

    # 自定义是否是超级管理员(request.user.is_superuser)
    # 'api.permissions.IsSuperUserPermission'

    # 自定义是否是管理员组员(request.user.groups.filter(name='管理员'))
    # 'api.permissions.IsGroupAdminUser',
],

}
2、新建py文件,并写入认证的权限类,这是下载setting中的全局认证

from rest_framework.permissions import BasePermission

class IsSuperUser(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_superuser

3、局部认证
在View文件中在需要认证的类中写入自己自定义的认证类
permission_classes = [permissions.IsSuperUserPermission]
4、全局权限认证,局部解除权限认证
permission_classes = ()

修复admin中密码明文显示的问题

ModelViewSet路由请求对应关系

无参:
{'get':'list','post':'create'}
有参:

posted @ 2019-08-19 22:18  Huanghongzheng  阅读(235)  评论(0编辑  收藏  举报