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.