gpt4 book ai didi

c# - 如何在 IAuthenticationFilter 实现中设置 WWW-Authentication header ?

转载 作者:太空狗 更新时间:2023-10-29 22:59:21 25 4
gpt4 key购买 nike

我正在使用 MVC5 的 IAuthenticationFilter 接口(interface)实现基本身份验证。我的理解是现在这是首选方法,而不是使用 DelegatingHandler。我已经开始工作了,但是响应中没有返回 www-authenticate header 。这是我对 ChallengeAsync 的实现:

public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
var result = await context.Result.ExecuteAsync(cancellationToken);
if (result.StatusCode == HttpStatusCode.Unauthorized)
{
result.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=localhost"));
}
}

如果我在 AuthenticateAsync 中设置 header ,则会返回 header ,但我认为我应该在 ChallengeAsync 中设置它。很难找到实现示例。

最佳答案

ChallengeAsync 中,将 context.Result 设置为 IHttpActionResult 类型的实例,如下所示。

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", "realm=localhost"));
}

return response;
}
}

关于c# - 如何在 IAuthenticationFilter 实现中设置 WWW-Authentication header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21712214/

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