{
var newTicket = new FormsAuthenticationTicket(1,
memberId.ToString(),
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
accountType,
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(newTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
HttpContext.Current.Response.Cookies.Add(cookie);
}
"UserData"这里为 accountType. 不能为Null 否则 Encrypt的时候会为null.
//Global.asax
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && authTicket.UserData != null)
{
var rehauIdentity = new RehauIdentity(HttpContext.Current.User.Identity) {AccountType = authTicket.UserData};
HttpContext.Current.User = rehauIdentity;
}
}
}
//IdentityClass
public class RehauIdentity : IPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return Roles.IsUserInRole(Identity.Name, role); }
public RehauIdentity(IIdentity identity) { this.Identity = identity; }
public string AccountType { set; get; }
}

本文介绍了一个使用ASP.NET Forms Authentication实现用户身份验证的过程。通过设置包含用户ID和账户类型的认证票据,并将其加密后存储在HTTP Cookie中。文章还展示了如何在每次请求时解密Cookie来恢复用户的身份信息。
8206

被折叠的 条评论
为什么被折叠?



