We have two separate websites / apps in same domain but different subdomains.
Eg
https://hello.website.com (Webapp 1)
https://world.website.com (Webapp 2)
What we'd like to do is to login users at Webapp 1 and upon logging in and clicking a button within Webapp 1, we'd like to redirect the user to Webapp 2. However, Webapp 2 needs the same authentication token which is currently stored in the localstorage of Webapp 1. How do I make the localstorage content available to Webapp 2?
Or is there a better way to do this?
Since the domains are not the same, transferring information from the local storage of one of them to another isn't possible directly , but since the sites are on HTTPS, it should be safe and easy enough to send the authentication token as search parameters. For example, when redirecting, instead of redirecting to https://world.website.com
, instead take the current authentication token for https://hello.website.com
and append it, then redirect:
const url = 'https://world.website.com?token=' + authToken;
window.location.href = url;
(if the authentication token may have special characters in it, you may need to escape them first)
Then, on the other domain, check to see if there's a token
in the search parameters, and if so, extract it and save it to localStorage:
const paramsMatch = window.location.href.match(/\?.+/);
if (paramsMatch) {
const params = new URLSearchParams(paramsMatch[0]);
const authToken = params.get('token');
if (authToken) {
localStorage.authToken = authToken;
}
}
Because the domains are on HTTPS, putting the token in the URL is safe - eavesdroppers will not be able to see it.
That's the limitation of localstorage
and sessionstorage
. You can't. There are some workarounds with iframe
, but those are neither elegant nor secured. You should use cookie with appropriate domain attribute domain=example.com
. You may also want to read the following answer for security with cookie vs localstorage: https://stackoverflow.com/a/54258744/1235935
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.