I have created an on-premise .Net 6 Web API and have successfully implemented authN using Azure (app registration > access_token). This api is accessed publically by an external vendor in a service-2-service way.
Because the controller actions need to have AuthZ using
When using the client app registrations client_id and client_secret I only receive the access_token, no information on roles!
{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 3599,
"access_token": "TOKENHERE"
}
What I need is proper Role checking using Role-based authorization without a user but I'm missing some crucial information on how to set this up properly on Azure and in the API bootstrapper. Roles, scopes, claims, ..?
What am I overlooking here?
CodePudding user response:
I tried to reproduce the same in my environment and got below results:
I created App roles
on the API App registration same as you like below:
I created another App registration for client and added Service.Read
role by granting consent like below:
I generated access token for the application using Client Credentials
grant type via Postman like below:
POST https://login.microsoftonline.com/<TenantID>/oauth2/v2.0/token
Using token endpoint URL, you will only get tokens in the response without displaying claims.
You can find the claims
like roles, scp etc... only when you decode the token like below:
In order to use the claims to authorize the actions in the API, you can build and register policies
like below:
In Program.cs:
builder.Services.AddAuthorization(options => { options.AddPolicy("Policy_Name", policy => policy.RequireClaim("Service.Read")); });
app.UseAuthorization();
In Controller file:
[Authorize(Policy = "Policy_Name")]
public class YourClass : Controller {}
Please refer the below documents to get complete code samples: