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.
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
}
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
}
});
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With