.net - 无法使用基本身份验证进行身份验证

标签 .net authentication iis asp.net-web-api httpmodule

我有一个需要 http 基本身份验证的 ASP.NET WebApi 服务(这是为了演示,而不是为了生产,所以这是基本身份验证的原因,而不是更安全的东西)。该服务在 Visual Studio IIS Express 服务器上运行良好,身份验证通过自定义 HTTP 模块进行。

当我将站点部署到托管服务器时,它失败并继续弹出登录屏幕。我用 Fiddler 验证了正在发送请求和正在发送凭据。但它一直以 401 未经授权的响应进行响应。看起来请求凭据在从客户端到服务器的过程中以某种方式丢失了。我花了很多很多时间来尝试对此进行诊断,而使用 Web API 和 IIS 进行的 .NET 身份验证似乎非常令人困惑。请帮忙!!

Fiddler 发出的请求显示:

获取我的网站地址 HTTP/1.1
主持人:我的网址
用户代理:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
接受:/
接受语言:en-US,en;q=0.5
接受编码:gzip、deflate
授权:基本 YmJvbm5ldDE4Om9jdG9iZXIxNw==
X-Requested-With: XMLHttpRequest
Referer: 我的网站
连接:保持事件状态

这是我配置的相关部分(如果需要我可以发布更多):

<modules>
  <add name="BasicAuthHttpModule" type="ITMService.Modules.BasicAuthHttpModule"/>
</modules>

<httpModules>
  <add name="BasicAuthHttpModule" type="ITMService.Modules.BasicAuthHttpModule"/>
</httpModules>

<authentication mode="Windows"/>

我的自定义 http 模块(在 visual studio 的测试中也工作正常)。这主要取自 example on asp.net :

namespace ITMService.Modules
{
public class BasicAuthHttpModule : IHttpModule
{

    private const string Realm = "www.mysite.net";

    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += OnApplicationAuthenticateRequest;
        context.EndRequest += OnApplicationEndRequest;

    }

    private static void SetPrincipal(IPrincipal principal)
    {
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
            Log.LogIt("current principal: " + principal.Identity.Name);
        }
    }


    private static bool CheckPassword(string username, string password)
    {
        string passHash = AuthUser.GetUserPassword(username);
        if (PasswordHash.ValidatePassword(password, passHash))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    private static bool AuthenticateUser(string credentials)
    {
        bool validated = false;

        try
        {
            var encoding = Encoding.GetEncoding("iso-8859-1");
            credentials = encoding.GetString(Convert.FromBase64String(credentials));

            int separator = credentials.IndexOf(':');
            string name = credentials.Substring(0, separator);
            string password = credentials.Substring(separator + 1);

            validated = CheckPassword(name, password);

            if (validated)
            {
                var identity = new GenericIdentity(name);
                SetPrincipal(new GenericPrincipal(identity, null));
            }
        }
        catch (FormatException)
        {
            // Credentials were not formatted correctly.
            validated = false;
            Log.LogIt("not validated");

        }
        return validated;
    }

    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));
        }
    }

    public void Dispose()
    {
    }
}
}

我的 IIS 服务器托管并以集成管道模式运行 .NET 4。我禁用了表单例份验证和模拟。我在服务器上启用了基本身份验证和匿名身份验证方法。

我已经阅读了无数关于此的论坛回复和帖子,但没有任何内容让我得出明确的答案。

最佳答案

我看到两个 www-Authenticate 响应 header 。我相信您的 HTTP 模块正在添加一个,而 IIS 正在添加一个。确保在 IIS 中禁用所有类型的身份验证,就像这样。我的猜测是您在 IIS 中启用了基本身份验证。

enter image description here

关于.net - 无法使用基本身份验证进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16905978/

相关文章:

asp.net - 小写 URL 的 IIS 重写规则

c# - 使用 Angular2 进行 Azure IIS 路由 --> 404

.net - ASP.NET - 上传大文件时如何显示错误页面(超过最大请求长度)?

asp.net - Web 应用程序问题(web.config 错误) 使用 IIS7.5 和 ASP.NET v2 的 HTTP 500.19

c# - 我还需要 Microsoft.Bcl.Build in .net 4.5+

c# - 使用 "Negotiate Authorization"发送 HTTP 请求

wordpress - 使用电话号码而不是用户名登录 WordPress

authentication - OAuth2 不同的客户端认证方式

.net - 如何在没有代码分析警告的情况下一起使用 StringWriter 和 HtmlWriter

.net - 打开.NET 4.0项目时,Visual Studio 2010错误: “Project Target Framework Not Installed”