【问题标题】:How do I set the WWW-Authentication header in an IAuthenticationFilter implementation?如何在 IAuthenticationFilter 实现中设置 WWW-Authentication 标头?
【发布时间】:2014-03-09 20:24:59
【问题描述】:

我正在使用 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 中设置它。很难找到示例实现。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多