0

I would like to create a Web API that can be accessed either using a Bearer token OR a simple API Key, for API key see https://gist.github.com/GeorgDangl/87db6426962bf50933b093e0952570e1. I understand how to implement both approaches individually however my question is how do I apply an Authorize attribute to my controller class that allows either of these methods. My understanding is the that Authorise attributes are accumulative ie if I apply both it will mean the request requires a Bear token AND an API key. I want it to work so that if the request has a Bearer token OR an API key then it authenticates successfully.

1 Answer 1

1

No, you can use a single authorization policy that specifies different authentication schemes and authenticating successfully with one of those will be enough to continue at which point the requirements of the authorization policy are checked for authorization.

When the authorization happens, the logic used by both the authorization middleware and the authorize filter looks like this (slightly simplified):

var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, httpContext);

if (HasAllowAnonymous(context))
    return;

var authorizeResult = await policyEvaluator.AuthorizeAsync(
        policy, authenticateResult, httpContext, context);

if (authorizeResult.Challenged)
    // trigger Challenge (401)
else if (authorizeResult.Forbidden)
    // trigger Forbid (403)

First, the policy evaluator is asked to authenticate the user for the policy, and then the returned result is being used to authorize the user. Authentication in the policy evaluator works like this:

  1. For each AuthenticationScheme in the policy, try to authenticate the user.
  2. For all succeeded authentications, merge their user principals into a single principal.
  3. Policy authentication was successful if a principal was created, i.e. at least one authentication was successful.

So in this process, all authentication schemes will be used to authenticate the user. They can be authenticated through only one scheme, e.g. Bearer and ApiKey, or they could even be authenticated through multiple schemes.

Then, the policy evaluator authorizes the user, by simply calling the authorization service to authorize the user against the policy’s requirements. And the policy requirements does not contain the authentication scheme that you hae built the policy with.

So to summarize: No, the authentication schemes you pass to the AuthorizationPolicyBuilder are only used for authentication, but not for authorization, and they will be all used to potentially authenticate the user.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.