AuthenticateRequest和AuthorizeAttribute之间丢失了自定义主体

时间:2013-10-31 15:53:16

标签: c# asp.net-mvc asp.net-mvc-4 iis

我有一个asp.net mvc 4网络应用,其中我有一个包含加密用户信息的自定义身份验证Cookie。在我的Global.asax.cs中,我解密了cookie,创建了自定义标识和主体,并在上下文中设置它。这一切都适用于运行IIS 7.5的本地计算机,但是当我使用IIS 8发布到我的登台设置时,自定义主体不会保留在上下文中。这是我的代码的要点

代码示例

protected void Application_BeginRequest(object sender, EventArgs e)
{
    AuthenticateRequest(HttpContext.Current);
}

public virtual void AuthenticateRequest(HttpContext context)
{
    var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (cookie == null || string.IsNullOrWhiteSpace(cookie.Value))
    {
        return;
    }

    var rawJson = DecryptAuthCookie(cookie.value);
    var stub = AuthenticationStub.FromString(rawJson);

    var context = HttpContext.Current;

    var identity = new CustomIdentity(stub.Username, stub.FirstName, 
                          stub.LastName, stub.Email, stub.UserId, stub.UserType);

    var principal = new CustomPrincipal(identity);

    context.User = principal;
}

此时我可以连接一个远程调试器,看看一切都设置正确。 context.UserCustomPrincipal

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {   
        // httpContext.User is a 
        // System.Security.Principal.GenericPrincipal not CustomPrincipal 
        return base.AuthorizeCore(httpContext);
    }
}

当我到达此处时,我可以看到httpContext.UserSystem.Security.Principal.GenericPrincipal而非CustomPrincipal这只发生在IIS 8计算机上,当我在本地运行时它是{{ 1}}如预期的那样。

介于CustomPrincipalAuthenticateRequest之间的某个地方,我的自定义校长已被删除,我不知道为什么。

有没有人有这方面的经验?我所有的都是疯狂的猜测。

1 个答案:

答案 0 :(得分:3)

你不知道,你正在与其他HttpModules战斗。尝试将代码从AuthenticateRequest移动到PostAuthenticateRequest。

相关问题