如何设置在IAuthenticationFilter实现WWW-认证头? [英] How do I set the WWW-Authentication header in an IAuthenticationFilter implementation?

查看:157
本文介绍了如何设置在IAuthenticationFilter实现WWW-认证头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实施使用MVC5的IAuthenticationFilter接口基本身份验证。我的理解是,这是现在的preferred方法,而不是使用DelegatingHandler。我知道了工作,但WWW身份验证头不会在响应中返回。这是我实现ChallengeAsync的:

I'm implementing basic authentication using MVC5's IAuthenticationFilter interface. My understanding is that this is now the preferred approach instead of using a DelegatingHandler. I've got it working but the www-authenticate header is not being returned in the response. This is my implementation of 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。实现范例已经很难找到。

The header is returned if I set it in AuthenticateAsync but I think I'm supposed to set it in ChallengeAsync. Sample implementations have been hard to find.

推荐答案

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

这篇关于如何设置在IAuthenticationFilter实现WWW-认证头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆