Cannot Return HTTP Unauthorized from Delegation Handler Web API

I am trying to implement authentication in DelegatingHandler. The following is an example.

public class AuthHandler: DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var auth = request.Headers.Authorization;
        if (!auth.Scheme.Equals("UberSecureScheme"))
        {
            return new Task<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("You have no token")
                });
        }

        return base.SendAsync(request, cancellationToken);
    } 
}

This never completes the task, and no response is returned. If I change the code to complete some task of continuing the task, for example, I saw several examples, Controller is executed first.

return base.SendAsync(request, cancellationToken)
           .ContinueWith(task =>
           {
               var response = task.Result;
               response.StatusCode = HttpStatusCode.Unauthorized;
               return response;
           });

This is obviously a disaster. I cannot allow someone to remove, and then tell them that they were unauthorized for this.

I also came across someone saying that just throws an HTTPResponseException. No matter what status code I enter there (404, 401, regardless), the browser always receives 500 internal server errors.

+4
2
if (!auth.Scheme.Equals("UberSecureScheme"))
{
    var response = request.CreateResponse(HttpStatusCode.Unauthorized);
    response.ReasonPhrase = "You have no token";
    return Task.FromResult<HttpResponseMessage>(response);
}
+7

Async/wait. , / - , , , ....:)

protected async override Task<HttpResponseMessage>              SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
var response = await base.SendAsync(request, cancellationToken);
if (HttpContext.Current.User == null) {
    HttpResponseMessage errorResponse = new HttpResponseMessage();
    errorResponse.Headers.Add("WWW-Authenticate", "Some auth related message");
    errorResponse.StatusCode = HttpStatusCode.Unauthorized;
    return errorResponse;
}
return response;
0

All Articles