Trying to open new window with Authorization header (react) from application to connect user on our website

Viewed 3802

Context issue : We have an app using React and axios to do some requests from our API. We also have a website which is online and ok. I need to develop the "Account" part of the app but time and money are missing. Solution is to do a link in the app that redirect to the "Account" part of the website.

So I have to pass Authorization Header with the Bearer Token in my request, and then open this window with the token. But I really can't make this work. I tried with axios but I'm not really comfortable with it (not me who develop the whole app). So I try with the old XMLHttpRequest().

<a onClick={this.onRedirectAccount}>

onRedirectAccount = e => {

     e.preventDefault();
     var redirectAccountUrl = "urlToMyAccountOnWebsite";
     const http = new XMLHttpRequest();
     http.open("GET", redirectAccountUrl);
     http.withCredentials = true;
     http.setRequestHeader("Accept", "application/json, text/plain, */*");
     http.setRequestHeader('authorization', 'Bearer '+ localStorage.getItem("token") );
     http.send();
     window.open(redirectAccountUrl);

If I do the request on Postman, I can see I am connected as user. I am also connected as user when I look at the preview of my request in the browser. But the window which is opening still tell me I'm not connected. I guess it's because my window.open doesn't keep the Authorization header on itself.

Have you got any ideas what I'm doing wrong, any clue to solve this ? Thank you and please feel free to ask for more details if needed.

1 Answers

You want to redirect user to urlToMyAccountOnWebsite. You can not set HTTP request headers unless you are making an async request.

A solution, send your token as a get parameter. Change your url which to be redirected like that:

yourSite.com/account?token=someTokenString then, handle and use it in the redirected page.

Related