gpt4 book ai didi

android - Web API 2 身份验证过滤器 - 存在授权 header 时 AuthenticateAsync 不触发

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:17 25 4
gpt4 key购买 nike

当网站在我的本地 IIS 上运行时,我遇到了一个简单的身份验证过滤器未触发的奇怪问题。如果我发布到 Azure,身份验证过滤器工作正常。所以我怀疑本地 IIS 上的设置,但除了在网站的身份验证设置下启用“基本身份验证”之外,我真的不知道它可能是什么其他设置。

我创建了一个空的 Web API 2 网站,它创建了值 Controller 。然后我为身份验证过滤器添加了以下样板代码:-

public class BasicAuthenticationAttribute : Attribute, IAuthenticationFilter
{

public bool AllowMultiple { get { return false; } }

public Task AuthenticateAsync(HttpAuthenticationContext context,
CancellationToken cancellationToken)
{
var req = context.Request;
// Get credential from the Authorization header
//(if present) and authenticate
if (req.Headers.Authorization != null &&
"Basic".Equals(req.Headers.Authorization.Scheme,
StringComparison.OrdinalIgnoreCase))
{
if (TryValidateCredentials(req.Headers.Authorization.Parameter))
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, "AuthenticatedUser"),
new Claim(ClaimTypes.Role, "user")
};
var id = new ClaimsIdentity(claims, "Token");
var principal = new ClaimsPrincipal(new[] { id });
// The request message contains valid credential
context.Principal = principal;
}
else
{
// The request message contains invalid credential
context.ErrorResult = new UnauthorizedResult(
new AuthenticationHeaderValue[0], context.Request);
}
}
return Task.FromResult(0);
}
private bool TryValidateCredentials(string creds)
{
string pair;

try
{
pair = Encoding.UTF8.GetString(Convert.FromBase64String(creds));
}
catch (FormatException)
{
return false;
}
catch (ArgumentException)
{
return false;
}
var ix = pair.IndexOf(':');
if (ix == -1) return false;
var username = pair.Substring(0, ix);
var pw = pair.Substring(ix + 1);
if (username != "" && pw != "")
{
return true;
}
else
{
return false;
}
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
context.Result = new ResultWithChallenge(context.Result);
return Task.FromResult(0);
}
public class ResultWithChallenge : IHttpActionResult
{
private readonly IHttpActionResult next;
public ResultWithChallenge(IHttpActionResult next)
{
this.next = next;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await next.ExecuteAsync(cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.WwwAuthenticate.Add(
new AuthenticationHeaderValue("Basic", "Please supply valid credentials"));
}
return response;
}
}

}

然后我在 ValuesController 类前面添加了以下属性:-

[TestBA.Filters.BasicAuthentication]
[Authorize]

我的默认 IIS7 网站(Windows 7 家庭高级版)指向项目文件夹,如果我运行和调试 w3wp.exe(托管 v4)然后访问网站 http://192.168.1.11/api/values导致在命中 AuthenticateAsync 开始处的断点。如果我从 Android 代码调用,我也会遇到相同的断点。但是,如果我使用 AsyncHttpClient.setBasicAuth 设置基本身份验证 header 或手动添加 header ,则断点永远不会被击中,我会立即收到未经授权的 HTTP 响应。如果我将网站发布到 Azure,那么它可以正常工作,因此未调用 AuthenticateAsync 的未经授权的响应只会发生在我的本地 IIS 上。如果有帮助,这里是 Android 代码:-

private void setBasicAuth(AsyncHttpClient client){
client.setBasicAuth("test", "test");
/*client.addHeader("Authorization",
"Basic " + android.util.Base64.encodeToString(
"test:test".getBytes(),
android.util.Base64.NO_WRAP
)
);*/
}

我什至在 Visual Studio Community 2013 中打开了所有可能的异常,以查看我是否缺少运行时异常或 native 代码异常,但什么也没有。如果有任何相关性,我将在 Android 上使用 loopj 库。此外,如果有任何相关性,我也在原生 Android IDE“AIDE”上编写 Android 代码。 IIS 日志显示请求正在传入并以 401 响应,无论我使用或不使用基本身份验证 header 进行调用,因此请求在这两种情况下都有效。

如果有人能阐明为什么当在 IIS 本地副本的请求中指定基本身份验证 header 时 Web API 2 身份验证过滤器不会触发,我将非常感激。

最佳答案

我在我的工作 PC 上重写了测试应用程序并且无法让它失败,所以这是一个发现差异的案例。

答案其实很明显。我在我的本地 IIS 上盲目启用了“基本身份验证”,因为我自然想在我的 Web API 2 网站中使用基本身份验证。错误的!在 IIS 中启用基本身份验证会告诉 IIS 拦截和处理所有基本身份验证 header ,而不将它们传递到网站。它实际上试图将用户名和密码与本地 PC 用户帐户相匹配。我需要的是在 IIS 中禁用基本身份验证,然后允许授权 HTTP header 传递到我的网站并导致 AuthenticateAsync 启动。

关于android - Web API 2 身份验证过滤器 - 存在授权 header 时 AuthenticateAsync 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29197708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com