HttpContext.Current.User is null under windows aut

2019-02-15 16:02发布

问题:

In the web.config:

<configuration>
    <authentication mode="Windows">
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
</configuration>

in global.asax

protected void Application_AuthenticateRequest(object sender, EventArgs args)
{
    tracker.LogRequest(HttpContext.Current.User, DateTime.Now)
    ///THIS IS ALWAYS NULL!!!
}

I am just really confused by this, any ideas?

回答1:

I think this is a symptom of listening on the wrong event. You should probably listen for Application.PostAuthenticateRequest.

Running a sample piece of code using a project I have that authenticates against my local domain's Active Directory to ask if the User object is nothing:

Code

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    Debug.WriteLine("Authenticate Request: " & (HttpContext.Current.User Is Nothing))
End Sub

Sub Application_PostAuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    Debug.WriteLine("Post-authenticate Request: " & (HttpContext.Current.User Is Nothing))
End Sub

Output

Authenticate Request: True

Post-authenticate Request: False

Following the PostAuthenticateRequest event, the HttpContext.Current.User.Identity property is an instance of System.Security.Principal.GenericIdentity for unauthenticated requests.