Cyn*_*hia 13 asp.net authentication forms-authentication asp.net-mvc-2
好的,这是我创建身份验证cookie的代码:
// get user's role
List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName));
List<string> rolesList = (from r in roles
select r.ToString()).ToList();
string[] rolesArr = rolesList.ToArray();
// create encryption cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddDays(90),
createPersistentCookie,
String.Join(";",rolesArr) //user's roles
);
// add cookie to response stream
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
//FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
Run Code Online (Sandbox Code Playgroud)
这是我在Global.asax中的代码,用于将用户角色设置为用户身份:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
catch
{
return;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果顶部示例中的"createPersistentCookie"为TRUE,则不会创建持久性cookie.如果我取消注释最后一行,如下所示:
//System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
Run Code Online (Sandbox Code Playgroud)
然后在我的硬盘上创建持久性cookie.但是在Global.asax代码中,"authTicket"中的UserData字段为空,因此我无法正确设置角色!
所以我必须使用SetAuthCookie来创建一个持久性cookie,但由于某种原因,UserData字段从持久性cookie中消失.
这是什么答案?
Dar*_*rov 17
要创建持久性cookie,您需要设置Expires属性:
if (authTicket.IsPersistent)
{
authCookie.Expires = authTicket.Expiration;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6606 次 |
| 最近记录: |