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
  • User signin with id and password
  • Server sends a token if user is authenticated
  • 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
  • localStorage
  • sessionStorage
  • 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){
        //
    }
     
    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
    ....
    The Solution
    We have currently two solutions to this problem
  • Redux or any other state management library
  • 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
  • Make a POST request to the server
  • Get the token and store it in a variable (token)
  • Assign it to window window.token = token
  • Now, you can use this any where..
  • 17

    This website collects cookies to deliver better user experience

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