gpt4 book ai didi

python - 使用 Django REST Framework 的 TokenAuthentication 查询字符串中的 token

转载 作者:太空狗 更新时间:2023-10-29 22:04:07 24 4
gpt4 key购买 nike

在使用 Django REST Framework 构建的 API 中可以使用 TokenAuthentication 方法进行身份验证。它的documentation表示身份验证 token 应通过 Authorization header 发送。

通常可以通过查询字符串发送 API key 或 token 以进行身份​​验证,例如 https://domain.com/v1/resource?api-key=lala

有没有办法对 Django REST Framework 的 TokenAuthentication 做同样的事情?

最佳答案

默认情况下,DRF 不支持查询字符串进行身份验证,但您可以轻松地覆盖 TokenAuthentication 类中的 authenticate 方法来支持它。

一个例子是:

class TokenAuthSupportQueryString(TokenAuthentication):
"""
Extend the TokenAuthentication class to support querystring authentication
in the form of "http://www.example.com/?auth_token=<token_key>"
"""
def authenticate(self, request):
# Check if 'token_auth' is in the request query params.
# Give precedence to 'Authorization' header.
if 'auth_token' in request.query_params and \
'HTTP_AUTHORIZATION' not in request.META:
return self.authenticate_credentials(request.query_params.get('auth_token'))
else:
return super(TokenAuthSupportQueryString, self).authenticate(request)

关于python - 使用 Django REST Framework 的 TokenAuthentication 查询字符串中的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433416/

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