如何使用VS调试服务器实现基本的HTTP身份验证?

ano*_*krB 3 c# asp.net authentication basic-authentication visual-studio

我正在为ActiveX HTTP控件制作测试装备,我需要创建一个安全POST的网站.为了简单起见,我正在使用VS调试服务器运行Web应用程序; Web应用程序项目是测试应用程序解决方案的一部分.AX控件不支持NTLM身份验证.有没有简单的方法可以在没有NTLM或重定向到页面表单的情况下要求非常基本的http身份验证?我只需要在帖子中要求用户名和密码.用户名和密码内容无关紧要,因此所有内容都将以明文形式存储.

我在Web.Config中尝试过身份验证模式; Windows看起来与NTLM相同(可能是错误的),Forms需要一个表单来连接并设置一个cookie,Passport超出了这个项目的范围,我不知道我是如何实现None的.有任何想法吗?

我在Web.Config中尝试了"authentication mode ="Windows"",并在Web应用程序的"Web"选项卡中选中了NTLM复选框.

Mic*_*out 6

您可以使用ASP.NET实现自己的基本HTTP身份验证.它似乎不是一个非常复杂的规范,但请参阅RFC1945了解所有细节.

如果我必须这样做,我会从HttpModule每个请求运行一个并检查HTTP标头HTTP_AUTHORIZATION.如果它是基本身份验证的标头,那么您可以解码用户名和密码.如果标头丢失或用户名和密码不正确,则发回HTTP 401响应并添加WWW-Authenticate标头.

像这样的东西(没有经过测试,但你明白了):

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)