Neo
Neo

Reputation: 16219

How to handle exception in IAuthenticationFilter interface?

I have created custom Authentication class using IAuthenticationFilter interface.

instead of using ChallengeAsync I have directly throw exception how to handle it ?

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
    HttpRequestMessage request = context.Request;
    AuthenticationHeaderValue authorization = request.Headers.Authorization;
    if (authorization == null)
    {
           throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,"FAIL"));
    }


public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
        //var challenge = new AuthenticationHeaderValue("Basic");
        //context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);
        //return Task.FromResult(0);
}

but how to handle exception throw?

Upvotes: 0

Views: 434

Answers (1)

Ivan R.
Ivan R.

Reputation: 1915

From documentation: The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.
So you do not need to handle this exception. From ChallengeAsync code, I suppose you want to add authentication header to response if request was unauthorized. You can implement it like

public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
    HttpRequestMessage request = context.Request;
    var challenge = new AuthenticationHeaderValue("Basic");
    var response = request.CreateResponse(HttpStatusCode.BadRequest, "FAIL");
    response.Headers.WwwAuthenticate.Add(challenge);
    throw new HttpResponseException(response);
}

Upvotes: 2

Related Questions