我正在为 ActiveX HTTP 控件制作测试装置,我需要创建一个网站以安全地发布到。为了简单起见,我使用 VS 调试服务器运行 Web 应用程序; Web 应用程序项目是带有测试应用程序的解决方案的一部分。 AX 控件不支持 NTLM 身份验证。有没有简单的方法来要求非常基本的 http 身份验证而无需 NTLM 或重定向到页面表单?我只需要它在发帖时要求输入用户名和密码。用户名和密码内容无关紧要,因此所有内容都将以明文形式存储。
我试过Web.Config中的认证方式; Windows 看起来与 NTLM 相同(那里可能是错误的),Forms 需要一个表单来连接和设置 cookie,Passport 超出了这个项目的范围,我不知道我将如何实现 None。有什么想法吗?
我在 Web.Config 中尝试了“authentication mode="Windows"",并选中了网络应用程序的“Web”选项卡中的 NTLM 复选框。
最佳答案
您可以使用 ASP.NET 实现您自己的基本 HTTP 身份验证。它doesn't seem就像一个非常复杂的规范,但请参阅 RFC1945了解所有详情。
如果我必须这样做,我会从一个 HttpModule
开始,它在每个请求上运行并检查 HTTP header HTTP_AUTHORIZATION
。如果它是基本身份验证的 header ,那么您可以解码用户名和密码。如果 header 丢失或用户名和密码不正确,那么您将发回 HTTP 401 响应并添加 WWW-Authenticate
header 。
类似这样的事情(未经测试,但你明白了):
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
}
}
关于c# - 如何使用 VS 调试服务器实现基本的 HTTP 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8809717/