4

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.

Gilgamesh
  • 121
  • 2
  • 2
  • 10

1 Answers1

3

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

Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34
  • Does it suppose to go like this? Visit W3Schools – Gilgamesh Jul 10 '18 at 20:35
  • I guess, No. Check this https://stackoverflow.com/questions/10093053/add-header-in-ajax-request-with-jquery – Umair Mohammad Jul 11 '18 at 05:27
  • Sorry for being annoyingly stupid. One more question. Am I suppose to write that ajax code for every single endpoint individually or there is a way to cover all the endpoint in one code? My guess is I'm suppose make a list of all endpoints and assign it to a variable, and then pass that variable in place of url. – Gilgamesh Jul 11 '18 at 18:04
  • Yes, you can define a separate function to take url, headers, data, request method [as per your requirements] and then call that function by passing the values as arguments. – Umair Mohammad Jul 11 '18 at 18:41
  • Happy to debug together. No issues. :) – Umair Mohammad Jul 11 '18 at 18:41