简体   繁体   English

ASP.NET MVC 5 - 如何让用户保持登录状态

[英]ASP.NET MVC 5 - How to keep user logged in

I am creating website where people can register and log in. I am using a SQL Server database with Entity Framework.我正在创建人们可以注册和登录的网站。我正在使用带有实体框架的 SQL Server 数据库。

Here is my Action for login in这是我的登录操作

[HttpPost]
public ActionResult LoggingIn(User user)
{
    ModelState.Clear();
    var result = MainLogic.LogIn(user);
    if (result.MessegeID == 0)
    {
        RedirectToAction("Index");
    }
    else
        ViewBag.LoginInfo = result.Msg;

    return View("Index");
}

Now I want the logged in user to be logged in for x time.现在我希望登录用户登录 x 时间。 I`ve been trying to do it with TempData[LoggedAs] = user and every time the user switches view I had TempData.Keep() until the user sign out.我一直在尝试使用 TempData[LoggedAs] = user 来做这件事,每次用户切换视图时,我都会使用 TempData.Keep() 直到用户退出。

I don't think its good practice, how else I can hold the user?我认为这不是一个好习惯,否则我怎么能抓住用户呢?

You need to set a session variable when login is successful.登录成功时需要设置会话变量。 Then you check if that session variable is set, if not, you send them to your login page.然后您检查该会话变量是否已设置,如果没有,则将它们发送到您的登录页面。 This might help you https://codereview.stackexchange.com/questions/51331/simple-authentication-in-asp-net-mvc-5这可能对您有帮助https://codereview.stackexchange.com/questions/51331/simple-authentication-in-asp-net-mvc-5

This is the very basic idea and hope this made some sense for you.这是非常基本的想法,希望这对您有所帮助。

I Think it's not a good idea to use your own authentication system since you haven't a lot of knowledge in this staff, I recommend Identity to manage users authentication, there are two points to consider when persisting user login :我认为使用自己的身份验证系统不是一个好主意,因为您对这个员工的了解不多,我建议使用 Identity 来管理用户身份验证,在坚持用户登录时需要考虑两点:

  1. Set the expire time for cookies设置cookies的过期时间

In the ConfigureAuth method of Startup class, set the expire time for cookies :Startup类的ConfigureAuth方法中,设置 cookie 的过期时间:

 public void ConfigureAuth(IAppBuilder app)
    {
     app.UseCookieAuthentication(new CookieAuthenticationOptions
         {
             AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
             LoginPath = new PathString("/Account/Login"),
             ExpireTimeSpan = new System.TimeSpan(90, 0, 0, 0),
             CookieHttpOnly = false,
             SlidingExpiration = true,
          });
     }
  1. Set the machine key in IIS, more details here在 IIS 中设置机器密钥,更多细节在这里

Use sessions and cookies.使用会话和 cookie。 As far as I know session time out is 20 min if you don't explicitly mention it.据我所知,如果您没有明确提及会话超时时间为 20 分钟。 Cookies can have more timeout period than session. Cookie 可以有比会话更长的超时时间。 So my best bet is to use cookies in your app and pay attention in security and best practices also.所以我最好的选择是在你的应用程序中使用 cookie,并注意安全和最佳实践。

You can also use cookies to manage logging.您还可以使用 cookie 来管理日志记录。 create a cookie创建一个cookie

HttpCookie cookie = new HttpCookie("Cookie");

Inital its value, you can store user ID or any unique data of user who have logged in.初始化其值,您可以存储用户 ID 或已登录用户的任何唯一数据。

cookie.Value = "user data";
cookie.Expires = DateTime.Now.AddSeconds(10);//You can set expire in seconds, hours or days etc. as per your choice. Cookie will get expire as per the time you have set.

Set in reponse to add cookie.设置响应添加cookie。

 this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

To access cookie Check the cookie if exists访问 cookie 检查 cookie 是否存在

if (Request.Cookies["Cookie"] != null) { 


}else{

string temp = Request.Cookies["Cookie"].Value; // access the value of cookie

}

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

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