Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store auth token (frontend) and how to put it in http headers of multiple endpoints?

I wanted to write auth backend for both mobile and webapp, so I decided to go with the DRF (Django Rest Framework) token authentication.

I pretty much figured out backend via DRF documentation but regarding frontend implementation it just says "include token in the header of every http request to the API."


So my question is

  1. When I retrieve token in AJAX call where should I store it so that upon browser refresh it doesn't disappear?
    (Apparently I'm not using cookies, because phones have restriction on cookie uses )
  2. How to insert the auth token in the http headers of multiple API endpoints?

With the help of Stackoverflow I figured out how to insert auth token in a single http header.

$.ajax({
  url: "https://www.something.com/random",
  type: 'get',
  headers: {
    token: "t&jdd9HJKHdss7hkjjkhdshgs",
  }
});

I was wondering If I have to write this piece of code for every endpoints or is there a way cover all the endpoints without being redundant?

like image 354
Gilgamesh Avatar asked Jan 28 '23 18:01

Gilgamesh


1 Answers

There are three ways how to store a token in a browser:

  1. LocalStorage - stores data with no expiration date, no access from a backend.
  2. SessionStorage - stores data until browser/tab is open, no access from a backend.
  3. Cookie - stores data, expiration time can be set individually, automatically sent with subsequent requests to the server.

More here: https://scotch.io/@PratyushB/local-storage-vs-session-storage-vs-cookie

So, the only Cookie would do it automatically for you, all the rest - you would need to provide manually.

You can choose from both LocalStorage and SessionStorage, but if you want your users to be logged in next time they open a page - I would choose a LocalStorage.

Then it needs to be added manually to every API request, but you can create a helper function to make it easier:

function apiRequest(type, url) {
  return $.ajax({
    url: url,
    type: type,
    headers: {
      token: localStorage.getItem("token"),
    }
  });
}

apiRequest("get","https://www.something.com/random").done(function(data) {
  console.log(data) 
})

More about localStorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

like image 73
Ivan Sorokin Avatar answered Jan 30 '23 09:01

Ivan Sorokin