francisco.preller
francisco.preller

Reputation: 6639

Asp.Net Identity - How to set Unauthorized programmatically?

I have a Web API 2 application which uses Asp.Net Identity for Authentication and Authorization. I also have a custom Message Handler to do an additional custom check to finalize the authentication (as well as parse some API data that is necessary to connect to the right schema on a multi-tenancy data store).

Here is my working code for the message handler:

public class AuthenticationHeadersHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Headers.Contains("Authorization"))
        {
            // Authenticate
            var auth = request.GetOwinContext().Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType);

            // Get user ID from token
            identityId = auth.Result.Identity.GetUserId();

            // Please note, the oAuth token would have successfully authenticated by now

            // ... Do some custom authentication and data gathering
            if (failedCheck)
            {
                // If user fails checks, I would like to force Asp.Net Identity to
                // return 401 not authorized here, or flag the request as not authorized
            }
        }
    }
}

Considering the code above, how can I manually flag the request as unauthorized even if it passed the initial authentication?

Upvotes: 0

Views: 766

Answers (1)

Kevin Junghans
Kevin Junghans

Reputation: 17540

I think this should work:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    if (request.Headers.Contains("Authorization"))
    {
        // Authenticate
        var auth = request.GetOwinContext().Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType);

        // Get user ID from token
        identityId = auth.Result.Identity.GetUserId();

        // Please note, the oAuth token would have successfully authenticated by now

        // ... Do some custom authentication and data gathering
        if (failedCheck)
        {
            // Return 401 not authorized here.
            return new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
    }
    // If we got here send an HTTP status of 200
    return new HttpResponsMessage(HttpStatusCode.OK);
}

Upvotes: 1

Related Questions