How to pass token to new tab in same browser (Login Issue) - javascript

I am learning web development and implementing the login functionality. I have a rest service which generates a unique token for each user which logs in. Now I had one issue if I log in one tab and go to homepage and if I go to another tab, instead of getting redirected to home page I was getting redirected to log in page again in the new tab. Ideally, if I go to another tab I should get redirected to home page. It happened because I was saving unique token in session storage. But I realized that session storage is per tab basis so now I am saving the token received from Rest service in local storage.
Below is what I did:
Before redirecting to login page I am checking if token exist in local storage
if((localStorage.getItem('p_kt')))
window.location = "pages/firstDashboard.html";
If token does not exists normal login code runs and I get the token from REST Service
localStorage.setItem('p_kt', self.get('tokenProp'));
Also, when some one logs out I do:
localStorage.clear();
So everything seems to be working now. But I doubt its the right way to fix the issue. Can someone guide me. Is it okey to keep token in local storage.

Related

Keep user logged in after refresh browser for Microsoft Graph API?

I followed the tutorial to Build JavaScript single-page apps with Microsoft Graph, and use it for my real project.
With this tutorial, I could able to create the web app for login user and create a calendar event. The problem is the session is always quickly expired as soon as I refresh so that I have to login again and again. Is there any way I can keep user still login after refresh browser. I wish it just like the google calendar id here that can keep user signed in even after fresh browser. Thanks.
Use localStorage to store the logged in user details. On refresh or the first visit to your site, first check to see if the details are available in local storage. If they are available, then log in the user automatically. Otherwise request the user to login and save the details in local storage.

How to get authentication token from front end while the user is logged in

I am trying to build a simple project where a user can search a movie from an api and add the selected movie to their "/movies" page, after being logged in.
I am using Nodejs, mongodb, express for backend and vanilla javascript for the front end.
When the user is registered or logged-in I am creating a JWT token and adding the token to the database.
My goal is to redirect them to their home page, which is "/user/movies"
Assume the user has logged in the first time, and it closed the
website, after some time has passed (not enough to expire the token)
the user opened the website again and went to "/user/movies" (which
requires an authentication.)
My question is, how would we still keep authenticated with the user after re-visiting, how can we reach the token that is previously created?
When I use postman, I can manually check the token from the database and enter the Authorization token to header and send a post request to validate the user.
But in the browser, how can I reach my previously created token to validate the user again?
I have tried localStorage but, in order to save token to the
localStorage, I need to take it from the database, but you can't
change localStorage in the backend.
I have tried cookies with http-only flag, but then how can I reach
the token from the front-end, since http-only, restrains from using javascript
What are my options in order to reach a JWT token from the front-end so that I can keep the user still authenticated, even after they close the website and come back later. (not enough to expire the token)
I am very new to how authentication works If I am making a logical mistake please tell me.
You need to send JWT token along with your other data as a response from your login API. Once you receive the response on the front end then just store the JWT Token to the localStorage by "localStorage.setItem("token",response.data.token).
Now you can always reference localStorage.getItem("token") to get the token even user close the browser and comeback again. Please do not forget to clear this localStoage by localStorage.removeItem("token") when user logout.
Also please note to not provide any expiry during the JWT token creation otherwise even you store that locally in localStorage then also it will get expire on server side and give "Forbidden error"
When you authenticate the user for the first time, store the token in the localStorage.
And since localStorage's data never gets deleted on its own, you can listen to the event of DOMContentLoaded where you can retrieve the token from the localStorage and authenticate the user with it, when the page is revisited.
You can read more about localStorage here

MSAL.js How to access SID received in other tab?

I'm trying to implement MSAL in a client side library, which works pretty well so far.
Now for my next steps I'm trying to add SSO by following the documentation at https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-js-sso#automatically-select-account-on-azure-ad
In this documentation it is pointed out that I can add the sid claim to the auth requests, and reuse that sid in my second tab when logging in.
Now my main question is: what is the process to access the sid retrieved in tab A, and then re-use it in tab B?
I'll summarize for anyone else that is running into this sort of situation. The traditional way to store login tokens is in a cookie. This works fine for most scenarios- if the user tries to login to a different site on the same domain, the cookie is picked up. If they are signing in to a different domain, they will still need to visit the login page, but instead of entering their credentials they will simply be issued a new cookie for the new domain.
The question posed is for a special case when attempting to obtain a cookie on one tab, then using it on another tab without refreshing the page in the second tab. In this case, the token must be stored in local storage in order to be accessible to the code in the second tab immediately.

Send JWT token to server upon initial browser request (using local storage)

Okay, let's say I have a login page where when the user logs in he or she gets a JWT token from the server which is then saved in local storage (I know cookies is better but I want to do it with local storage). After that, imagine I quit my browser (token is still in local storage and in this example has no expiration date). Now what I want is the following: After quitting the browser (but I got successfully logged in and have token in local storage) how do I make it so that upon initial request to the same server I don't get the login page up again but instead have the user already signed in? Taje into an account that I am able to authenticate the user after the first request and I am aware how but How do I send the token in the initial request?
There may not be a direct solution to your requirement.
But, One hack can be added by adding Script in Head tag.
And withing this script you check if localStorage.getItem('key') is present or not.
If value is present send the request to Home Page directly along with Token or else Login Page.
But, this script download is extra server round-trip.

New tab opens login page even though already logged in another tab

I am new to web development and I am trying to implement log in functionality. I have successfully implemented the log in functionality. When I open www.bla.com/login I am able to log in post which gets redirected to the homepage.
Problem: If open another tab and type: www.bla.com/login it again opens login page. Ideally if I am logged into one of the tab, I should be redirected to homepage irrespective the url being pointed to login page.
P.S: I am not sure what chunk of code I need to share here because I am not sure what causes this issue. Please help or let me know if I need to post my code base. I am using JavaScript and backbone as front end.
EDIT
I have a REST Service which gets hit when I login and REST service gives me back a User Specific Token. I use this user specific token to again call another Rest Service to fetch more user specific data.
So, basically I need to put a check on this token received. The token received I have stored in browser session. But when I go to another tab and try to access that token its NULL. So I am assuming every tab in browser does not share the session storage. If Yes, then where shall I place this Token so that if someone hits the login page I should check whether a token already exists. if exists then redirect to home page. Kindly guide.
It is hard to say without seeing your code, so let me make an educated guess:
Most likely you do not create cookie with some sessionId after user is successfully logged in.
This cookie would be then used in every request sent to the server, to prove that user is indeed authenticated.
When you open a new tab and there is no cookie/session created, than this new instance of application has no knowledge of the other instance, where user is already logged in.
You may want to look at this answer
EDIT
Maybe you are using sessionStorage instead of cookies. At least I would say so, when I read about behaviour of your app.
See the docs for session storage
The sessionStorage property allows you to access a session Storage
object. sessionStorage is similar to Window.localStorage, the only
difference is while data stored in localStorage has no expiration set,
data stored in sessionStorage gets cleared when the page session ends.
A page session lasts for as long as the browser is open and survives
over page reloads and restores. Opening a page in a new tab or window
will cause a new session to be initiated, which differs from how
session cookies work.
So make sure that you application store the token either in cookies or in localStorage. And also that it correctly reads from them. Maybe the cookies is created, but never read?

Categories