如上所述,IIS内置的基本身份验证使用Windows凭据。这意味着您需要在托管服务器上为您的用户创建帐户。但对于互联网应用程序,用户帐户通常存储在外部数据库中。
以下代码如何执行基本身份验证的HTTP模块。您可以通过替换CheckPassword方法来轻松插入ASP.NET成员资格提供程序,该方法在本示例中是一个虚拟方法。
在Web API 2中,应考虑编写身份验证过滤器或OWIN中间件,而不是HTTP模块。
复制
C#
namespace WebHostBasicAuth.Modules
{
public> {
private const string Realm = "My Realm";
// TODO: Here is where you would validate the username and password.
private static bool CheckPassword(string username, string password)
{
return username == "user" && password == "password";
}
private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var request = HttpContext.Current.Request;
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
AuthenticateUser(authHeaderVal.Parameter);
}
}
}
// If the request was unauthorized, add the WWW-Authenticate header
// to the response.
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}