'How to redirect to new page with Authorization Headers after login?

I have a login page. On click of login button, the details are sent to server and are validated. A token is received in return after successful validation. I need to know how to redirect to a new page(/dashboard) using this token set as authorization header. Note that I am using vanilla Js

function login(){  
  var userEmail = document.getElementById("email_field").value;
  var userPass = document.getElementById("password_field").value;  
  axios
    .post('http://localhost:5000/login',{
        username: userEmail,
        password: userPass,
    })
    .then( (response) => {
        if(response.data.success){
            let token = response.data.token;
            localStorage.setItem("SavedToken", token);
            axios.defaults.headers.common['Authorization'] = token;
            
             //some code here to redirect to localhost:5000/dashboard with authorization header
        }
        alert(response.data.message);
        console.log(response)
    }) 
}


Solution 1:[1]

I had the same issue when I was writing vanilla authorization app.

From my experience there is no easy way to achieve this. The browser sends req and without us being able to meddle with the headers, without using http intercepting tool to catch outgoing browser http requests.

So, one way to allow to send http req and utilize the token we have is to use this work-around: the server serves HTML pages without any issue, but the body is empty. For each page the is a built in "onload" function. This function sends anther http req via "fetch" (or any other tools), and gets back the accual page after the token is validated by the server. Then you render the accual page into the body.

For Example:

fetch("http://localhost:5454/signup")
            .then((res) => res.json())
            .then((res) => {
              const token = res.token;
              localStorage.setItem("token", token);
              fetch("http://localhost:5454/", {
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer ${token}`,
                },
              })
                .then((res) => res.text())
                .then((rawHtml) => {
                  document.write(rawHtml);
                  document.close;
                });

Another way to do it without sending multiple http request to each endpoint is the single page approuch: You get only the main page of the application that has a nav bar in it. Each navbar click sends a req with the token and gets the HTML, and render is to a specific location within the main page.

As I said, this is a very crud way.

Another option is in the server, after the login and in the generation on the token - add the token to a cookie, that the browser will store, and will add to every outgoing request.

I will be glad to hear from anyone that has a better solution... ANyway, hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1