【问题标题】:What is the second 'auth' argument in the return signature of authentication.BaseAuthentication.authenticate?authentication.BaseAuthentication.authenticate 的返回签名中的第二个“auth”参数是什么?
【发布时间】:2014-04-21 09:01:32
【问题描述】:
【问题讨论】:
标签:
python
django
authentication
django-rest-framework
【解决方案1】:
阅读source。
我认为 auth 参数由使用 access_tokens 的身份验证方法使用。
我们来看一个例子。
class TokenAuthentication(BaseAuthentication):
"""
Simple token based authentication.
Clients should authenticate by passing the token key in the "Authorization"
HTTP header, prepended with the string "Token ". For example:
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
"""
model = Token
"""
A custom token model may be used, but must have the following properties.
* key -- The string identifying the token
* user -- The user to which the token belongs
"""
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'token':
return None
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid token header. Token string should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_credentials(auth[1])
def authenticate_credentials(self, key):
try:
token = self.model.objects.get(key=key)
except self.model.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')
if not token.user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted')
return (token.user, token)
def authenticate_header(self, request):
return 'Token'
您会看到 authenticate() 调用了 authenticate_credentials(),它返回了用户对象和访问令牌。