简体   繁体   English

检查用户是否在客户端登录

[英]Check if user has logged in on client side

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 ?是否有一种安全的方法来检查用户是否已登录应用程序,而不是检查用户机器中是否存在“sid”cookie?

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.纯 JS 或 JQuery 解决方案将不胜感激。

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 ).您可以为此使用浏览器本地存储 ( 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如果您使用的是 ASP.Net Identity,您可以按如下方式进行检查

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:在 JS 中:

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

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

It should 100% works它应该 100% 有效

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");
 }

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.在我看来,您应该将带有 expireDate 的authToken保存到本地存储中,然后在每次请求某些内容时检查它是否过期(不包括 GET),并且还与服务器验证authToken是否过期。 2 ways validation. 2种方式验证。

Client to client and client to server.客户端到客户端和客户端到服务器。 Both would be matched correctly.两者都将正确匹配。

解决方案是将此信息作为会话变量存储在服务器上(使用 php),然后使用 ajax 在 javascript 中检索此信息。

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.使用会话存储进行验证不是一个好方法 imo,因为它不在选项卡之间共享。

  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.当用户登录到您的网站并将请求发送到您的服务器时,生成一个以有效负载作为其电子邮件 ID 的 JWT 令牌,并将其作为 cookie/json 响应发送给客户端。

  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.如果您更喜欢 JWT 令牌作为响应,则将 JWT 令牌以唯一名称(例如 myAdminAccessToken)保存在本地存储中,这样它就不会干扰浏览器中的其他键。 A cookie in response is a much better and robust approach then storing JWT token与存储 JWT 令牌相比,作为响应的 cookie 是一种更好且更强大的方法

  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.现在,每次您的用户向您的服务器发出网络请求时,在进行网络调用(获取 url)之前检查令牌是否存在于本地存储中,如果不存在,则它们未被授权并将它们重定向到登录页面。 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.解析 cookie/JWT 令牌并验证电子邮件是否存在,这意味着他们已获得授权,发送一个 authorised:true 作为响应,并让他们从您的服务器获取请求资源。

  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.如果不存在此类电子邮件或 JWT 令牌解析失败,则表示他们未获得授权,并且他们试图绕过您的第一次验证检查,即步骤#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.在这种情况下,从您的服务器发送一个授权:假响应,并在收到授权失败后,您的客户端应该将它们注销并重定向到登录页面,并从本地存储中删除 accessToken。

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.我没有纯 js 或 jquery 代码,但如果你愿意,我可以与你分享反应代码,解释上述过程。

Optimisations优化

You can even optimise the above solution for more robust and secure app.您甚至可以优化上述解决方案以获得更强大和安全的应用程序。

  • use redis for caching user emails for quick validations.使用 redis 缓存用户电子邮件以进行快速验证。
  • use a state management library to provide an extra layer of protection and make your ui in sync.使用状态管理库提供额外的保护层并使您的 ui 同步。

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.本地存储、会话存储、状态管理库对于保护您的路由/数据并不可靠,但它们可用于减少对服务器的网络调用次数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM