Http模块认证

Ant*_*nto 2 c# httpmodule http-authentication

我正在使用这篇文章中的以下代码来尝试创建一个自定义 http 模块:

public class BasicAuthenticationModule: IHttpModule
{
  public void Init(HttpApplication application)
  {
    application.AuthenticateRequest += new EventHandler(Do_Authentication);
  }

  private void Do_Authentication(object sender, EventArgs e)
  {
    var request = HttpContext.Current.Request;
    string header = request.Headers["HTTP_AUTHORIZATION"];
    if(header != null && header.StartsWith("Basic "))
    {
      // Header is good, let's check username and password
      string username = DecodeFromHeader(header, "username");
      string password = DecodeFromHeader(header, password);

      if(Validate(username, password) 
      {
        // Create a custom IPrincipal object to carry the user's identity
        HttpContext.Current.User = new BasicPrincipal(username);
      }
      else
      {
        Protect();
      }
    }
    else
    {
      Protect();
    }
  }

  private void Protect()
  {
    response.StatusCode = 401;
    response.Headers.Add("WWW-Authenticate", "Basic realm=\"Test\"");
    response.Write("You must authenticate");
    response.End();
  }

  private void DecodeFromHeader()
  {
    // Figure this out based on spec
    // It's basically base 64 decode and split on the :
    throw new NotImplementedException();
  }

  private bool Validate(string username, string password)
  {
    return (username == "foo" && pasword == "bar");
  }

  public void Dispose() {}

  public class BasicPrincipal : IPrincipal
  {
    // Implement simple class to hold the user's identity
  }
}
Run Code Online (Sandbox Code Playgroud)

该代码可以使服务器返回 401 错误并弹出登录对话框,但是当输入正确的登录详细信息时,登录对话框不会消失。

在调试代码时,单击对话框上的“确定”按钮没有任何反应,未触发事件且未验证用户详细信息,我无法弄清楚为什么这不起作用。

任何帮助或想法都会很棒,谢谢。

ziv*_*kan 5

在 Microsoft 的 asp.net 网站上,有一个关于如何进行自定义身份验证很好示例。忽略它说它是关于 WebAPI 的事实。该代码使用 IHttpModule,因此它适用于 WebForms、IHttpHandler、asmx、WCF 以及在 IIS 中运行的任何其他内容。将该页面末尾的代码复制并粘贴到新项目中对我有用。虽然,我不建议像示例那样将线程的 CurrentPrincipal 设置为经过身份验证的用户。我更喜欢只使用当前上下文的 User 属性。

如果模块中的断点没有被命中,那么几乎可以肯定是因为 http 模块没有正确注册。我上面链接的 asp.net 页面显示了如何在您的 web.config 文件中注册该模块,因此您应该从那里开始。你应该能够使用 Visual Studio 的智能感知自动完成来完成你的类名,这有助于确保你输入正确(尽管 Resharper 有可能在我的机器上这样做,但我认为它只是简单的 Visual Studio) .