一、说明
认证只是验证用户身份信息、权限是可不可以访问。所有认证与权限要一起使用才起作用。
认证与权限的运行逻辑是先找局部、再找配置、最后找默认配置。
二、认证
- 功能:是通过用户提供的用户ID/密码组合或者是Token来验证用户的身份。
- 局部配置:在视图中添加以下代码
authentication_classes = [SessionAuthentication, BasicAuthentication]
from rest_framework.viewsets import ModelViewSet
class GameViewSet(ModelViewSet):
...
authentication_classes = [SessionAuthentication, BasicAuthentication]
#[SessionAuthentication, BasicAuthentication]是默认的验证方式,也可以添加自定义或第三方认定方式
- 全局配置:在settings.py中添加以下代码
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
#[SessionAuthentication, BasicAuthentication]是默认的验证方式,也可以添加自定义或第三方认定方式
]
}
- 自定义
如何自定义认证方案?
要实现自定义的认证方案,要继承BaseAuthentication类并且重写.authenticate(self,request)方
法。如果认证成功,该方法应返回(user, auth)的二元元组,否则返回None。
在某些情况下,你可能不想返回None,而是希望从.authenticate()方法抛出AuthenticationFailed异
常。
通常你应该采取的方法是:
- 如果不尝试验证,返回None。还将检查任何其他正在使用的身份验证方案。
- 如果尝试验证但失败,则抛出AuthenticationFailed异常。无论任何权限检查也不检查任何其他身份验证方案,立即返回错误响应。
你也可以重写.authenticate_header(self,request)方法。如果实现该方法,则应返回一个字符串,该字符串将用作HTTP 401 Unauthorized响应中的WWW-Authenticate头的值。
如果.authenticate_header()方法未被重写,则认证方案将在未验证的请求被拒绝访问时返回HTTP403Forbidden响应。
示例
#以下示例将以自定义请求标头中名称为'X_USERNAME'提供的用户名作为用户对任何传入请求进行身份验证,其它类似自定义认证需求比如支持用户同时按用户名或email进行验证。
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
#要继承BaseAuthentication
class ExampleAuthentication(authentication.BaseAuthentication):
#要调用authenticate是启用验证标准
def authenticate(self,request)
username = request.META. get(X USERNAME)
if not username
return None
try:
user = User.objects.get(username=username)
e cept User,DoesNotExist
raise exceptions.AuthentfcationFailed('No such user')
return (user, None)
三、权限
- 功能:权限(Permission)的校验发生验证用户身份以后,是由系统根据分配权限确定用户可以访问何种资源以及对这种资源进行何种操作,这个过程也被称为授权(Authorization)。
- 局部配置
from rest_framework.viewsets import ModelViewSet
class GameViewSet(ModelViewSet):
...
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
#[SessionAuthentication, BasicAuthentication]是默认的验证方式,也可以添加自定义或第三方认定方式
permission_classes = [IsAuthenticated]是局部权限类调用
3. 全局配置:在settings.py中添加以下代码
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
- 自定义
from rest_framework.permissions import BasePermission
class ReadOnly(BasePermission):
#has_permission是重写权限方法
def has_permission(self, request, view):
return request.method in SAFE_METHODS
- 以下是所有权限方法
AllowAny 不用谁上都可以访问,默认就是这个方法
IsAuthenticated 只用认证通过后才可以请求。
IsAdminUser 只有管理员才可以请求
IsAuthenticatedOrReadOnly 只用认证通过后才可以创建和修改数据,但所有人都可以读取数据。