TTT*_*TTT 6 python authentication django django-rest-framework
在使用Django REST Framework构建的API中,可以使用TokenAuthentication方法进行身份验证.它的文档说应该通过Authorization标头发送身份验证令牌.
通常,人们可以通过查询字符串发送API密钥或令牌以进行身份验证,例如https://domain.com/v1/resource?api-key=lala.
有没有办法对Django REST Framework的TokenAuthentication做同样的事情?
Omr*_*tix 11
通过聋人DRF不支持查询字符串进行身份验证,但您可以轻松地authenticate在TokenAuthentication类中覆盖他们的方法来支持它.
一个例子是:
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)
Run Code Online (Sandbox Code Playgroud)
class QueryStringBasedTokenAuthentication(TokenAuthentication):
def authenticate(self, request):
key = request.query_params.get('auth_token').strip()
if key:
return self.authenticate_credentials(key)
return False
Run Code Online (Sandbox Code Playgroud)
DRF有TokenAuthentication哪些查找token在header.该方法authenticate_credentials负责验证令牌.
| 归档时间: |
|
| 查看次数: |
3713 次 |
| 最近记录: |