我正在使用一个asp.net MVC应用程序,我编写了一个自定义actionfilter,以便根据在登录时设置的授权级别过滤掉某些控制器操作,并将其存储在formsauthentication cookie旁边的加密cookie中,两个cookie都被设置为具有相同的到期时间但由于某种原因,在一段空闲时间之后,授权cookie值变为空白,我无法调试并在行为中捕获它但它只是消失
我的actionfilter代码如下所示:
string usersRole = "";
if (filterContext.HttpContext.Session["role"] != null)
usersRole = filterContext.HttpContext.Session["role"].ToString();
else if (filterContext.HttpContext.Response.Cookies["ArisPortalCookie"].Value != null)
{
usersRole = filterContext.HttpContext.Response.Cookies["ArisPortalCookie"].Value;
filterContext.HttpContext.Session["role"] = usersRole;
}
string encryptedRole = EncryptionHelper.Encrypt(RoleToCheckFor);
if (encryptedRole == usersRole || usersRole == EncryptionHelper.Encrypt("Admin")) //if the user's role and role required match, we have success
{
//now we break down the response action based on what role was required
if (RoleToCheckFor == "Admin")
{
}
else if (RoleToCheckFor == "Tech" || RoleToCheckFor == "Admin")
{
}
else if (RoleToCheckFor == "Physician" || RoleToCheckFor == "Admin")
{
}
}
else
{
filterContext.Result = new ViewResult
{
ViewName = "NoAuth",
ViewData = filterContext.Controller.ViewData,
TempData = filterContext.Controller.TempData
};
}
答案 0 :(得分:2)
我也会这样做来存储角色。为什么要和他们并排?
我假设你正在做这样的事情:
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(60),
rememberMe,
roles);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
authenticationCookie.HttpOnly = true;
contextBase.Response.Cookies.Add(authenticationCookie);
如果您正在使用FormsAuthentication.SetAuthCookie
,我认为您不需要,我也不会,请确保您的配置超时设置为60分钟或等同于您的上述时间
从cookie中读取值(管道格式)(根据要求)
private static void ReadCookieForPrincipal()
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
// If the cookie can't be found, don't issue the ticket
if (authCookie == null) return;
// Get the authentication ticket and rebuild the principal & identity
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { '|' });
GenericIdentity userIdentity = new GenericIdentity(authTicket.Name);
GenericPrincipal userPrincipal = new GenericPrincipal(userIdentity, roles);
HttpContext.Current.User = userPrincipal;
}