DEV Community

Rahul kumar
Rahul kumar

Posted on

How can we use authentication token if cookie is blocked by user.

Authentication Token

Authentication Token is a non human readable text which contains some encrypted data. It is used to authenticate user for API access.
read-more-about-it

SPA

A single-page application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current web page with new data from the web server, instead of the default method of a web browser loading entire new pages.
wiki

Way to authenticate users using token

  1. User signin with id and password
  2. Server sends a token if user is authenticated
  3. On next http request, user sends token as header, query-parameter or by whatever way to authenticate with API's.

The way we store token in browser

  1. localStorage
  2. sessionStorage
  3. cookie

You can read about advantages and disadvantages over here

What's next?

All the above storage mechanism are depended on cookie. If cookie is blocked by user then your application will not function properly or it might break.

Suppose, user clicks on signin url and your server sends a token to the user in response. After getting the token, you will store the token on browser storage. But unfortunately your application can not store token, because user has blocked cookie and you might get error like below.
Error image

Your application will break here if you are not handeling them with try and catch 


// set
try{
    localStorage.token = "...";
}catch(e){
    //
}

// get
try{
    console.log(localStorage.token)
}catch(e){
    //
}
Enter fullscreen mode Exit fullscreen mode

 

If you are handeling web storage with try and catch then either you can prompt user to enable cookie or leave user as not authenticated. If user went on any other page and that page require authentication then again user has to  come at signin page.

Process continue...


Sign-in page > Authenticated page
Authenticated page -> Sign-in page
Sign-in page > Authenticated page
Authenticated page -> Sign-in page
....
Enter fullscreen mode Exit fullscreen mode

The Solution

We have currently two solutions to this problem

  1. Redux or any other state management library
  2. Window global variable

If you are using redux   then you need to write a lot of code.

If you are using window then you don't need to write...

Example

  1. Make a POST request to the server
  2. Get the token and store it in a variable (token)
  3. Assign it to window window.token = token
  4. Now, you can use this any where..

Top comments (0)