Jam*_*Ide 5 c# asp.net-mvc basic-authentication asp.net-web-api asp.net-mvc-5
我正在使用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"));
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在AuthenticateAsync中设置它,则会返回标头,但我认为我应该在ChallengeAsync中设置它.示例实现很难找到.
在ChallengeAsync,设置context.Result为类型的实例IHttpActionResult,如此.
public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
CancellationToken cancellationToken)
{
context.Result = new ResultWithChallenge(context.Result);
return Task.FromResult(0);
}
Run Code Online (Sandbox Code Playgroud)
像这样提供实现.
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;
}
}
Run Code Online (Sandbox Code Playgroud)