如何在MVC中永久保留已登录的用户? [英] How do I persist logged in user in MVC?

查看:45
本文介绍了如何在MVC中永久保留已登录的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立我的第一个MVC网站,我刚刚实现了一个安全控制器和视图.

I'm setting up my first MVC site and I just implemented a security controller and views.

但是,我不了解的是如何在控制器之间持久保存已登录的用户数据.

However what I don't understand is how I can persist the logged in user data across my controllers.

例如,用户使用电子邮件/密码登录.然后,我可以验证电子邮件和密码是否匹配,然后执行以下操作:

For example the user logs in with email/password. I can then verify that the email and passwords match and I do the following:

FormsAuthentication.SetAuthCookie(userLogin.UserName, false);
return View("../Home/Index");

例如,现在我要在索引"视图中显示仅用户可以看到的数据.

Now say for example I want in the Index view to present data that only a user can see.

我有一个表格设置,但是它是基于user_id的.

I have a table setup but it's based on the user_id.

我可以在他们登录时保存user_id还是我已经可以使用某些东西来访问他们的电子邮件(用户)?(然后,如有必要,我可以通过电子邮件查找ID)

Can I either save the user_id when they login or is there something already available to me to access their email(user)? (I could then look up the id via the email if necessary)

我的MVC已设置为进行表单身份验证:

My MVC is setup for Forms authentication:

<authentication mode="Forms">
  <forms loginUrl="~/Security/Login" timeout="2880" />
</authentication>

然后我用"[Authorize]"注解装饰了控制器.

and I decorated the controllers with the "[Authorize]" annotation.

推荐答案

FormsAuthentication.SetAuthCookie(userLogin.UserName, false);

上面的代码只是在cookie中设置身份验证票证.

Above code just sets authentication ticket inside cookie.

经过身份验证的用户发送请求后,您仍然需要从cookie中检索身份验证票证,并创建一个Principal对象.

Once authenticated user sends a request, you still need to retrieve auth ticket from cookie, and create a Principal object.

void Application_AuthenticateRequest(object sender, EventArgs e)
{
   HttpCookie decryptedCookie = 
      Context.Request.Cookies[FormsAuthentication.FormsCookieName];

   FormsAuthenticationTicket ticket = 
      FormsAuthentication.Decrypt(decryptedCookie.Value);

   var identity = new GenericIdentity(ticket.Name);
   var principal = new GenericPrincipal(identity, null);

   HttpContext.Current.User = principal;
   Thread.CurrentPrincipal =HttpContext.Current.User;
}

用法

if (User.Identity.IsAuthenticated) {
   var username = User.Identity.Name;
}

这篇关于如何在MVC中永久保留已登录的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆