Search code examples
javascriptsessionbackbone.jsauthenticationfrontend

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.


Solution

  • 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?