Windows (AD) Authentication and the Authorize Attribute–Login Popup
The [Authorize] attribute kept throwing a ‘login’ popup even though the user was logged in via windows authentication.
The problem is that the [Authorize] attribute uses the following line to determine if a user is logged in.
if (httpContext.User.Identity.IsAuthenticated)….
This returns TRUE ONLY for FORMS Authentication. It fails for Windows Authentication.
So – how do you check if you have a successfully logged in user?
This default check can be modified (by overriding the appropriate method)
- Write you own Authorize attribute.
- Override the AuthorizeCore method provided in the AuthorizeAttribute.
- Use Request.ServerVariables[“LOGON_USER”]; to check for the logged on user
public class CustomAuthorizeAttribute : AuthorizeAttribute { public bool IsValidUser { get; protected set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { base.AuthorizeCore(httpContext); if (httpContext == null) { throw new ArgumentNullException("httpContext"); } // Make sure Forms authentication shows the user as authenticated - Only works for FORMS auth, not for WINDOWS auth // if (httpContext.User.Identity.IsAuthenticated == false) return false; string user = httpContext.Request.ServerVariables["LOGON_USER"]; if(user != null) IsValidUser = true; return IsValidUser; }
Summary
The [Authorize] attribute is meant to provide a quick, declarative way of checking if the user (in the httpRequest) is correctly authenticated. If not, the user gets thrown to a login page or login popup (in a browser).
This attribute doesn’t quite work right when the default authentication is WINDOWS (instead of forms). To work around this obstacle, consider overriding the default behavior and checking for the logged on user in the Request variables collection.
Leave a Reply