2012-08-10 19 views
0

我有这个问题。当用户登录时,我使用formsauthanticationticket创建cookie:asp.net mvc3 Cookie过期后重定向用户

var formAuthTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(1), false, ""); 
        var encryptedFormAuthTicket = FormsAuthentication.Encrypt(formAuthTicket); 
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedFormAuthTicket); 
        Response.Cookies.Add(cookie); 
        return RedirectToAction("Index", "Home"); 

现在。在PreRequestHandlerExecute事件我检查,如果用户通过身份验证/ cookie存在。

var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     if (cookie != null) 
     { 

      var formAuthTicket = FormsAuthentication.Decrypt(cookie.Value); 
      var newFormAuthTicket = new FormsAuthenticationTicket(formAuthTicket.Version, formAuthTicket.Name, 
                    formAuthTicket.IssueDate, 
                    DateTime.Now.AddMinutes(1), 
                    formAuthTicket.IsPersistent, 
                    formAuthTicket.UserData, 
                    FormsAuthentication.FormsCookiePath); 
      cookie.Value = FormsAuthentication.Encrypt(newFormAuthTicket); 
      context.Response.Cookies.Set(cookie); 
     } 

但是,当饼干不存在/过期我想将用户重定向到登录页面,当他点击某个环节。任何想法? 感谢

编辑

因为我不能使用授权的属性。我知道这件事。我在程序集中有httpmodule,它在web项目中被引用。在httpmodule中我有Init方法,我在这里初始化PreRequestHandlerExecute()事件。如果我检查用户的身份验证。如果我在“else”中使用类似这样的内容 - > Response.Redirect(url),会发生循环重定向,这是错误的。 10分钟后没有任何请求,用户点击一些链接,他将被重定向到登录页面 - >这是我的问题,我无法解决。

+0

乔治是对的。您似乎要求的是表单身份验证的默认行为。 – 2012-08-10 14:39:38

+0

是的,我知道这种方法。但将来,这将是很多工作。 – Bxx 2012-08-10 15:50:07

回答

1

为什么你只是不使用[Authorize]属性?添加在你行动的迹象,如果有过期的认证相关的cookie将被自动重定向到登录页面

例如

[Authorize] 
public ActionResult Profile()  
{ 
} 

如果你需要一个定制的实现创建自定义属性实现接口例如

public class FooAuthorizeAttribute : AuthorizeAttribute 
{ 
    public string fooField{ get; set; } 

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    //Do my stuff 
} 

然后叫你的行动

[FooAuthorizeAttribute] 
public ActionResult Profile()  
{ 
} 
+0

因为我不能使用授权属性。我知道这件事。我在程序集中有httpmodule,它在web项目中被引用。在httpmodule中我有Init方法,我在这里初始化PreRequestHandlerExecute()事件。如果我检查用户的身份验证。如果我在“else”中使用类似这样的内容 - > Response.Redirect(url),会发生循环重定向,这是错误的。 10分钟后没有任何请求,用户点击一些链接,他将被重定向到登录页面 - >这是我的问题,我无法解决。 – Bxx 2012-08-10 15:04:43