我在 IIS7 中为我的站点启用了基本身份验证,并按照此链接为基本身份验证请求创建处理程序。问题是,无论用户输入什么凭据,即使输入了正确的凭据,站点也会不断返回 401。这只是一个测试,凭据会根据硬编码值进行检查。
以下是相关代码:
public class BasicAuthenticationHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest+=context_BeginRequest;
context.AuthenticateRequest += context_AuthenticateRequest;
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
TryAuthenticate(application);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
TryAuthenticate(application);
}
private static void TryAuthenticate(HttpApplication application)
{
if (!Authenticate(application.Context))
{
application.Context.Response.Status = "401 Unauthorized";
application.Context.Response.StatusCode = 401;
application.Context.Response.AddHeader("WWW-Authenticate", "Basic");
application.CompleteRequest();
}
}
private static bool Authenticate(HttpContext context)
{
if (context.User!=null && context.User.Identity.IsAuthenticated)
{
return true;
}
if (!context.Request.Headers.AllKeys.Contains("Authorization"))
return false;
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
IPrincipal principal;
if (TryGetPrincipal(authHeader, out principal))
{
context.User = principal;
return true;
}
return false;
}
private static bool TryGetPrincipal(string[] creds, out IPrincipal principal)
{
if (creds[0] == "Administrator" && creds[1] == "SecurePassword")
{
principal = new GenericPrincipal(
new GenericIdentity("Administrator"),
new string[] { "Administrator", "User" }
);
return true;
}
if (creds[0] == "BasicUser" && creds[1] == "Password")
{
principal = new GenericPrincipal(
new GenericIdentity("BasicUser"),
new string[] { "User", "SystemUser" }
);
return true;
}
else
{
principal = null;
return false;
}
}
当客户端输入正确的凭据(即“BasicUser”、“Password”)时,会创建 GenericPrincipal 对象并将其分配给 HttpContext 的 User 属性。调查 Request.IsAuthenticated 告诉它是true
.
这就是为什么我不明白为什么客户一次又一次地收到 401。
我不确定所有管道是如何工作的 - 可能是基本身份验证更进一步到一些也服务于请求的 IIS HttpModule?或者可能是代码不完整,context_BeginRequest
需要扩展?(我知道在 Forms 身份验证类型的情况下,您会执行 Response.Redirect(goodguy.aspx) 之类的操作)
无论如何,感谢任何帮助/问题。
忘了说在 web.config 我也放了
<system.webServer>
<modules>
<add name="BasicAuthenticationHttpModule" type="Analytics.BasicAuthenticationHttpModule" />
</modules>
</system.webServer>