“PostAuthenticateRequest"何时执行? [英] When `PostAuthenticateRequest` gets execute?

查看:30
本文介绍了“PostAuthenticateRequest"何时执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 Global.asax.cs 文件:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        ...
    }

    protected void Application_Start()
    {
        this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
    }

    // This method never called by requests...
    protected void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            var identity = new GenericIdentity(authTicket.Name, "Forms");
            var principal = new GenericPrincipal(identity, new string[] { });
            Context.User = principal;
        }
    }
}

PostAuthenticateRequest 什么时候执行?

推荐答案

根据 文档:

当安全模块具有建立了用户的身份.

Occurs when a security module has established the identity of the user.

...

PostAuthenticateRequest 事件是在 AuthenticateRequest 之后引发事件发生.功能订阅PostAuthenticateRequest 事件可以访问处理的任何数据PostAuthenticateRequest.

The PostAuthenticateRequest event is raised after the AuthenticateRequest event has occurred. Functionality that subscribes to the PostAuthenticateRequest event can access any data that is processed by the PostAuthenticateRequest.

这里是 ASP.NET 页面生命周期.

但是因为您的问题是用 ASP.NET MVC 标记的,所以我强烈建议您在自定义 [Authorize] 属性中执行此操作,而不是使用此事件.示例:

But because your question is tagged with ASP.NET MVC I would strongly recommend you performing this into a custom [Authorize] attribute instead of using this event. Example:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            var authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new GenericPrincipal(identity, new string[] { });
                httpContext.User = principal;
            }
        }
        return isAuthorized;
    }
}

现在用 [MyAuthorize] 属性装饰你的控制器/动作:

Now decorate your controllers/actions with the [MyAuthorize] attribute:

[MyAuthorize]
public ActionResult Foo()
{
    // if you got here the User property will be the custom
    // principal you injected in the authorize attribute
    ...
}

这篇关于“PostAuthenticateRequest"何时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆