本文介绍了使用Django REST Framework的TokenAuthentication在查询字符串中的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Django REST Framework 身份验证构建的API中,可以使用TokenAuthentication方法进行身份验证.它的文档表示应通过 Authorization 标头.

In an API built with Django REST Framework authentication can be done using the TokenAuthentication method. Its documentation says the authentication token should be sent via an Authorization header.

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

Often one can send API-keys or tokens via a query string in order to authenticate, like https://domain.com/v1/resource?api-key=lala.

是否可以使用Django REST Framework的TokenAuthentication进行相同的操作?

Is there a way to do the same with Django REST Framework's TokenAuthentication?

推荐答案

通过默认,DRF不支持查询字符串进行身份验证,但是您可以轻松地在 TokenAuthentication 类来支持它.

By deafult DRF doesn't support query string to authenticate, but you can easily override their authenticate method in TokenAuthentication class to support it.

一个例子是:

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)

这篇关于使用Django REST Framework的TokenAuthentication在查询字符串中的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:32