【问题标题】:Http module AuthenticationHttp模块认证
【发布时间】:2014-11-16 17:40:43
【问题描述】:

我正在使用this post 的以下代码来尝试创建自定义 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
  }
}

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

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

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

【问题讨论】:

    标签: c# httpmodule http-authentication


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 2019-01-21
      • 2013-06-15
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      相关资源
      最近更新 更多