Setting the result in the context of the ChallengeAsync method in the authentication filter

This question is related to the answer I provided here . Comment OP made me think a little. I suggested using a class that implements IHttpActionResult, as in the ChallengeAsyncauthentication filter method .

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

Instead, I can simplify ChallengeAsyncas follows.

public 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"));
    }
    context.Result = new ResponseMessageResult(result);
}

, IHttpActionResult, ? , - , , HttpResponseMessage . , IHttpActionResult, , , .

+4
1

, , . , . ( MVC), : http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/BasicAuthentication/ReadMe.txt

. ; , .

, :

  • MVC. MVC Web API , . MVC ResponseMessageResult (HttpContext , , HttpResponseMessage, , ). MVC- , , , - .
  • . ChallengeAsync , . , . , HttpRequestMessage ChallengeAsync , .

; : https://aspnetwebstack.codeplex.com/workitem/1456

+5

Source: https://habr.com/ru/post/1526569/


All Articles