asp.net-mvc - 记住我选项在 ASP .Net MVC 中不使用 cookie
问题描述
我使用 asp .net MVC 创建了登录,并为选择“记住我”选项的用户添加了一个 cookie。下面是用于添加 cookie 的代码
if (model.LoginViewModel.RememberMe)
{
var authTicket = new FormsAuthenticationTicket(
1,
model.LoginViewModel.Email,
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
model.LoginViewModel.RememberMe, //true to remember
"",
"/");
//encrypt the ticket and add it to a cookie
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
}
我也将此配置添加到 web.config 中。
<authentication mode="Forms">
<forms loginUrl="~/candidate" timeout="2880" />
</authentication>
当我第二次登录时,我仍然看不到我的登录详细信息。
我在这里错过了什么还是有其他方法可以做到这一点?
解决方案
使用 OWIN 复制 FormsAuthentication 的最低要求将使用与此类似的内容:
using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
//
using Microsoft.Owin.Security;
namespace YourProjectNamespace
{
public class ClaimsAuthManager
{
public void SignIn(string userName, string displayName = "", bool createPersistantLogin = false)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, userName));
claims.Add(new Claim(ClaimTypes.IsPersistent, createPersistantLogin.ToString()));
claims.Add(new Claim(ClaimTypes.GivenName, string.IsNullOrWhiteSpace(displayName) ? userName : displayName));
var identity = new ClaimsIdentity(claims, AuthenticationTypes.ApplicationCookie);
GetAuthenticationContext().SignIn(new AuthenticationProperties { IsPersistent = createPersistantLogin }, identity);
}
public void SignOut()
{
GetAuthenticationContext().SignOut(AuthenticationTypes.ApplicationCookie);
}
private IAuthenticationManager GetAuthenticationContext()
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
}
与 FormsAuthentication 不同,这不是静态/单例对象,因此您需要将其注入到控制器中,或者在每次要让用户登录或注销时创建一个新实例。像这样的东西:
new ClaimsAuthManager().SignIn(model.LoginViewModel.Email, null, model.LoginViewModel.RememberMe);
推荐阅读
- c++ - Implementing an initializer-list constructor that doesn't copy the elements
- javascript - 如何将数据格式化为给定的格式
- python - 为什么我不能在 greenlet 中使用 gevent websockets
- php - laravel中的根文件夹重定向问题
- python - Pytorch DataLoader - 处理单个批次
- python - 为所有行创建具有相同元组值的列
- c# - C# 如何检查空值。(值为空)或(空 == 值)。我们可以使用 `is` 运算符代替 == 运算符吗
- .net - 在 .NET 中安装 Nexmo Api 失败
- sql - PostgreSQL array_agg 但有停止条件
- css - 如何解析 CSS 以添加 CSS 选择器前缀