且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何设置在IAuthenticationFilter实现WWW-认证头?

更新时间:2022-04-17 23:02:58

ChallengeAsync ,设置 context.Result 以类型的实例 IHttpActionResult ,就像这样。

In ChallengeAsync, set context.Result to an instance of type IHttpActionResult, like so.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                                  CancellationToken cancellationToken)
{
    context.Result = new ResultWithChallenge(context.Result);
    return Task.FromResult(0);
}

提供实现,像这样。

Provide an implementation, like so.

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