我使用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不同的是,这不是一个staticsingleton对象,所以你需要将它注入到控制器中,或者在每次用户登录或退出时创建一个新的实例。就像这样。
new ClaimsAuthManager().SignIn(model.LoginViewModel.Email, null, model.LoginViewModel.RememberMe);