gpt4 book ai didi

python - authentication.BaseAuthentication.authenticate 的返回签名中的第二个 'auth' 参数是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:00 24 4
gpt4 key购买 nike

参见http://www.django-rest-framework.org/api-guide/authentication#example

“如果身份验证成功,该方法应返回(用户,身份验证)的二元组...”

return (user, None)

第二个“auth”参数到底是什么?在我见过的所有示例中,它始终为“无”。是否存在其他情况?

最佳答案

阅读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(),后者返回用户对象和访问 token 。

关于python - authentication.BaseAuthentication.authenticate 的返回签名中的第二个 'auth' 参数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23194109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com