Continuing the customization of the basic two tiers scenario introduced in my previous posts, I would like to talk about scopes. OAuth2 defines the concept of scope as a "list of space-delimited, case-sensitive strings" that specifies the scope of the access request. These scopes can be used by a target application to allow or deny the access to its resources. Hence, with the scopes we can fine-tune the API access based on the caller access token.
To make it simple:
- The target application (Api) defines which scopes supports (i.e.: "scopeA", "scopeB” ...)
- The client application (FrontEnd) specifies which scopes wants during the access token request **
- The authentication server (Azure AD) replies with an access token that contains a field (scp) with all the valid scopes
- The target application (Api) inspects the access token and takes the proper actions (allow, deny, redirect... etc)
Let's us start from the last step, the target application configuration.
From the point of view of the target application scopes are just strings (or better claims) part of the JWT token:
In Asp.Net Core 2.0 we can easily integrate the scopes control defining authorization policies in the Startup class:
and then use such policies to control the API access:
In this manner we are allowing to access to our API only the users that have the right scopes in the access token, otherwise a 403 forbidden message is returned.
So far so good. The next step is to tell Azure AD which are the supported scopes.
Technically speaking the scopes are just a JSON configuration in the application manifest (they are also called OAuth2Permissions):
This is sufficient to create the scopes and exposes them to other applications in the same tenant. The scopes become visible in the "Required Permissions" settings of the other applications.
We need to know that the scopes we select here are set as "default", that means every user will get such scopes in the access token, regardless of the client request.
A working and customizable example can be found here
** The V1.0 endpoint does not honor the scopes requested by the client; It always fills the "scp" field with the scopes defined in the portal. So, it is a static configuration: the scopes/permissions not selected in this tab cannot be requested by the caller.
*** The V2.0 endpoint honors the scopes in the client request as support dynamic and incremental consent pages