javascriptdjangodjango-rest-framework

How to add authorization token in incoming http request header


I'm implementing token authentication via DRF(Django-rest-framework). So far I've understood that in token authentication you exchange your credential with a token which server had had already generated for every user. Then you put that token in every request header to the API, without worrying about the cookies.

Now I know how to generate token and write to view to authenticate and issue token. However, I haven't figured out how to put token in the http header, which I suppose need to be done in front-end.

I tried to search but there doesn't seems to a clear answer on the internet how to do it.


Solution

  • You need to provide that token in the Authorization header

    Example :

    headers = {
        "Authorization": "Token " + token
    }
    
    # or, depends upon specific Token Authentication that you're using
    headers = {
        "Authorization": "Bearer " + token
    }
    

    And then send this as header, something like this

    response = requests.get(url, headers=headers)
    

    for ajax requests check this out Add Header in AJAX Request with jQuery