标签:mission dde protocol 视图 response html header and 情况下
认证是将一个传入的请求和一组标识凭据相关联的机制,比如请求过来的用户,或者用户登录时携带的token。
然后权限策略就能使用这些凭据来决定是否允许这个请求。
REST框架提供了多种开箱即用的方案,也允许你实施自定义的方案。
认证总是在view的最开始运行,在权限检查之前,在其他任何代码被允许执行之前。
request.user属性通常会被设为contrib.auth 包下的User类。
request.auth属性被用做额外的认证信息。比如,作为一个请求签名的认证token
记住一点,认证机制自己并没有允许或不允许一个传入的请求,它只是简单的标识请求携带的凭据。
认证方案总是被定义为一组类。REST框架会尝试用每一个类来认证,然后使用第一个成功认证的类的返回值来设置request.user 和request.auth。
如果没有类认证,request.user 会被设为 django.contrib.auth.models.AnonymousUser一个实例,request.auth 会设置为 None.
默认的认证方案会被全局设置,使用DEFAULT_AUTHENTICATION_CLASSES 设置。比如:
REST_FRAMEWORK = {
‘DEFAULT_AUTHENTICATION_CLASSES‘: (
‘rest_framework.authentication.BasicAuthentication‘,
‘rest_framework.authentication.SessionAuthentication‘,
)
}
你也可以在一个rer-view或者per-viewset上设置认证方案,使用APIView类视图
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)
当一个未被认证的请求被拒绝时,有两种合适的error code
401返回必须包含一个WWW-Authenticate header,指导客户端需要如何认证。
403返回没有包含WWW-Authenticate header。
使用哪种返回,取决于认证方案。虽然有多种认证方案在使用,但可能只有一个方案用于决定返回的类型。
在确定响应类型时,将使用视图上设置的第一个身份验证类。
注意:当一个请求被成功认证时,但还是被拒绝执行请求,这种情况下,不论时哪种认证方案,总是使用403返回。
这个方案使用HTTP Basic Authentication,使用用户的username和password进行签名。一般只适合用于测试。
如果成功认证,它会提供以下凭据:
request.user will be a Django User instance.request.auth will be None.未认证时返回401,带一个WWW-Authenticate header。比如:
WWW-Authenticate: Basic realm="api"
单单使用一个token-based HTTP认证方案。
使用这个方案,需要在认证类中包含TokenAuthentication,此外在INSTALLED_APPS 设置中包含rest_framework.authtoken
INSTALLED_APPS = (
...
‘rest_framework.authtoken‘
)
Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations.
你还需要为你的用户创建token
from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key)
标签:mission dde protocol 视图 response html header and 情况下
原文地址:https://www.cnblogs.com/jabbok/p/10795440.html