9

Is there a safe way to check if the user has logged into the application rather than checking if "sid" cookie exists in user's machine ?

I want to allow the user to proceed on certain links on a page only if they have logged in.

I do the login validation on the server side but want to avoid the request trip.

Pure JS or JQuery solution would be appreciated.

Thank you.

Me Unagi
  • 615
  • 2
  • 7
  • 18

7 Answers7

12

Please try this

Put this code after user first log in

jQuery(window).load(function() {
  sessionStorage.setItem('status','loggedIn') 
});

When ever user clicks a link you can check like

if (sessionStorage.getItem('status') != null))
    //redirect to page
}
else{
    //show validation message
}
Rino Raj
  • 6,264
  • 2
  • 27
  • 42
  • 4
    You should be aware that session storage is not shared across tabs. If the user does an 'open in new tab', the new tab won't have the session storage value. There are ways to copy session storage from one tab to another using local storage as an intermediatiary. See https://stackoverflow.com/questions/20325763/browser-sessionstorage-share-between-tabs – Connell.O'Donnell Feb 10 '21 at 16:30
3

As you ask for a "safe way": No. You should always validate the user's session on the server side for all requests.

Something you could do though is to adapt the front end to the users current status. For example change the "Login"-Link to a "Logout"-Link. For this to work you could set some king of flag on the users machine. You could use the browser local storage for this (http://www.w3schools.com/html/html5_webstorage.asp).

Something else you could for example do is, to change the behavior of for example links:

$("a").click(function(e){
    if(localStorage.getItem("isLoggedIn") !== true) {
        e.preventDefault();
        // this prevents navigation and you can now do your js stuff here
    }
});
newBee
  • 1,289
  • 1
  • 14
  • 31
  • That answer should be the accepted one, for the question was how to do the check safely, and it is not possible indeed (client code cannot be trusted ; setting/reading a piece of information on the client, be it in/from a cookie, local storage, etc. is not going to change that). The security model relies on the client execution stack (eg. the browser, for instance) to not be tampered (ie. install a safe, open-source or trustable browser), and on the network stack as well (see middleman => https://) – chikamichi Apr 15 '20 at 19:09
  • I disagree. The server can still implement the checks for whether the user is logged in, but the client needs some type of state to know whether to clear its state and render the guest view or maintain the user view. – user823447 Apr 28 '23 at 07:08
3

if you are using ASP.Net Identity you can check it as follows

In Razor :

@inject SignInManager<ApplicationUser> SignInManager

@if (SignInManager.IsSignedIn(User))
        {
            <input type="hidden" id="logged" value="true" />
        }
        else
        {
            <input type="hidden" id="logged" value="false" />
        }

In JS:

function check() {
var signed = $('#logged').val();

if (signed === 'true') {
    //What you want to do
}
else {
    window.location.href = "/YourController/YourAction?ReturnUrl=/YourReturnUrl;
}
} 
Hasan_H
  • 77
  • 4
0

It should 100% works

Put this code after user Login Page(Login page Nextpage)

jQuery(window).load(function() {
  sessionStorage.setItem('status','loggedIn') 
 });

When ever user clicks a link you can check any page with bellow code(Any page)

if (sessionStorage.getItem('status') != null){
//redirect to page
alert("Is Login : True");
 }
 else{
  //show validation message
 alert("Is Login : False");
 }
Suresh Gopineni
  • 139
  • 2
  • 6
0

In my opinion you should save to your local storage an authToken with it expirationDate and then check if it expired or not every time you request something (GET not included) and also validate with the server if the authToken is expired or not. 2 ways validation.

Client to client and client to server. Both would be matched correctly.

Danto
  • 9
0

The solution is to store this information on the server as a session variable(using php), and then retrieving this information in javascript using ajax.

JorensM
  • 330
  • 4
  • 15
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 04 '21 at 17:13
0

I'll share my approach for client side validating while reducing the number of call to server. Validating with session storage is not a good approach imo as it is not shared between tabs.

  1. When the user logs in to your website and send the request to your server, generate a JWT token with payload as their email id and send it as cookie/json response to client.

  2. If you prefer JWT token in response then save the JWT token in local-Storage with a unique name (eg. myAdminAccessToken) so it doesn't interfere with other keys in their browser. A cookie in response is a much better and robust approach then storing JWT token

  3. Now every time your user makes a network request to your server, before making the network call (fetching the url) check if the token exist in the local-Storage, if not then they are not authorised and redirect them to login page. and if it exist allow them to make the network call to your server.

  4. Parse the cookie/JWT token and validate if the email exist then it means they are authorised send a authorised:true in response and let them fetch the request resource from your server.

  5. If no such email exist or the JWT token parsing failed it means they are not authorised and they tried to bypass your first validation check, which is in step#3.

  6. In this case send a authorised:false response from your server and upon receiving failed authorised your client should log them out and redirect to login page and also remove the accessToken from local-Storage.

i don't have pure js or jquery code for this but if you want i can share react code with you explaining the above mentioned process.

Optimisations

You can even optimise the above solution for more robust and secure app.

  • use redis for caching user emails for quick validations.
  • use a state management library to provide an extra layer of protection and make your ui in sync.

local-storage, session-storage, state-management libraries are not reliable for protecting your routes/data but they can be used to reduce the no of network calls to your server.