现在授权cookie已过期 - 用户被重定向到默认登录页面。
我想抓住这样的时刻,并在登录页面上告知用户因超时而被重定向。
我实现了自定义AuthorizeAttribute:
public class CustomAuthorizeAttribute : AuthorizeAttribute {
public override void OnAuthorization( AuthorizationContext filterContext ) {
var cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket.Expired) {
//TODO redirect to Account/LogOn with some flag
但无论cookie是如何设置的(持久性或非持久性),如果过期则为null,如果未过期则为null。因此,我无法达到(ticket.Expired)的时刻,因为那时它是空的。
答案 0 :(得分:0)
if(filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName] == null)
{
Response.Redirect("login.aspx?expired=true");
}
在login.aspx
- 页面上:
在Page_Load
:
string expired = Request.QueryString["expired"].ToString();
if(expired == "true")
{
//Show Message
}
答案 1 :(得分:0)
使用filterContext
:
var cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
//not logged.
if (cookie == null)
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "area", "" }, { "controller", "Account" }, { "action", "LogOn" }, { "returnUri", filterContext.HttpContext.Request.RawUrl }});
FormsAuthenticationTicket ticket = null;
ticket = FormsAuthentication.Decrypt(cookie.Value);
//not logged.
if (ticket == null)
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "area", "" }, { "controller", "Account" }, { "action", "LogOn" }, { "returnUri", filterContext.HttpContext.Request.RawUrl }});
//logged, but expired.
if (ticket.Expiration > DateTime.Now) {
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "area", "" }, { "controller", "Account" }, { "action", "LogOn" }, { "returnUri", filterContext.HttpContext.Request.RawUrl }, { "alert", "Session expired"} });
}
答案 2 :(得分:0)
看起来我发现了什么问题,当Application_BeginRequest过期时仍然可以使用cookie但是在Application_AuthenticateRequest中它已经为空(有些东西正在删除它)所以我将放置重定向逻辑进入Application_BeginRequest