如何在IAuthenticationFilter实现中设置WWW-Authentication标头?

时间:2014-02-11 20:21:45

标签: c# asp.net-mvc asp.net-web-api asp.net-mvc-5 basic-authentication

我正在使用MVC5的IAuthenticationFilter接口实现基本身份验证。我的理解是,现在这是首选方法,而不是使用DelegatingHandler。我已经开始工作,但响应中没有返回www-authenticate标头。这是我对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中设置它,则会返回标头,但我认为我应该在ChallengeAsync中设置它。样本实现很难找到。

1 个答案:

答案 0 :(得分:7)

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