Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token in query string with Django REST Framework's TokenAuthentication

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.

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.

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

like image 553
TTT Avatar asked Apr 03 '15 13:04

TTT


People also ask

How do I get authentication token in Django REST Framework?

This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations.

How JWT token works in Django REST Framework?

After verifying the credentials, the server issues two JSON Web Tokens to the user. One of them is an Access Token and the other is a Refresh Token. The frontend of your application then stores the tokens securely and sends the Access Token in the Authorization header of all requests it then sends to the server.

How does token authentication work in Django?

Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.


1 Answers

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

An example would be:

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)
like image 173
OmriToptix Avatar answered Sep 29 '22 08:09

OmriToptix