3

我正在使用MVC5的IAuthenticationFilter接口实现基本认证。我的理解是,这是现在的首选方法,而不是使用DelegatingHandler。我已经得到它的工作,但www-authenticate头没有在响应中返回。这是我实现ChallengeAsync的:如果我在AuthenticateAsync设置返回如何在IAuthenticationFilter实现中设置WWW身份验证标头?

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

的头,但我觉得我应该将其设置为ChallengeAsync。示例实现很难找到。

回答

6

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

谢谢!看起来他们可能已经实现了这一点,但这个解决方案运行良好。 –

+0

如果你想让它变得更容易,可以为这个工作项目投票:https://aspnetwebstack.codeplex.com/workitem/1456 – dmatson

+0

@JamieIde:请参阅David的答案 - http:// stackoverflow。 COM/A/21742491。 – Badri