When `PostAuthenticateRequest` gets execute?

前端 未结 2 1318
小蘑菇
小蘑菇 2020-11-30 07:18

This is my Global.asax.cs file:

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


        
2条回答
  •  無奈伤痛
    2020-11-30 07:31

    According to the documentation:

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

    ...

    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.

    And here's the ASP.NET Page Life Cycle.

    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;
        }
    }
    

    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
        ...
    }
    

提交回复
热议问题