权限认证类必须是可插拔的,钩子
1 简介
身份认证的原理是将用户请求和一系列认证证书联系起来。比如说一个用户发送了一个请求,或者说是带着token的请求。权限管理类( permission)和节流(throttling )策略能够使用它们的证书来决定这个请求是否被许可。
REST框架提供了大量用户认证方案,也允许用户实现自定义方案。
身份认证一般在视图函数处理请求中的顺序十分靠前,在 permission and throttling之前,更在其他代码执行之前。
request.user一般由contrib.auth包中的User设置
request.auth被用来添加各种附加的身份认证信息。比如说他可以用来表示request携带的身份认证token
注意:authentication自身并不会判断接收不接收用户的请求,他只是简单的标识用户所用的凭证
1 身份认证是怎样进行的?
authentication方案总是定义成一个类的列表。REST框架会尝试认证列表中的每一个类。如果第一个类就认证成功了,就会设置request.user和request.auth信息
如果没有一个类认证成功,request.user就会设置为django.contrib.auth.models.AnonymousUser,request.auth将会设置为None.
对于未经用户认证的请求,其request.user和request.auth值可以通过UNAUTHENTICATED_USER和 UNAUTHENTICATED_TOKEN进行设置。
默认的认证方案,可以使用DEFAULT_AUTHENTICATION_CLASSES进行设置。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
也可以为每一个视图函数或者视图类设置认证方案。
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
# @api_view装饰器
@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
@permission_classes((IsAuthenticated,))
def example_view(request, format