ʃʈɑɲ
ʃʈɑɲ

Reputation: 2684

.Net 6 Web API configuration for service-2-service AuthN/AuthZ using Azure

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 RBAC (Role-based access control) I started searching on how to accomplish this for my scenario.

What I did is, create app roles on the API app registration and create a 2nd app registration (client) that has a "Read" role, now I can generate a separate access_token but it seems I have no way to check the role in the API?

enter image description here

Client app regstration

When using the client app registrations client_id and client_secret I only receive the access_token, no information on roles!

enter image description here

{
    "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?

Upvotes: 0

Views: 414

Answers (1)

Sridevi
Sridevi

Reputation: 22452

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:

enter image description here

I created another App registration for client and added Service.Read role by granting consent like below:

enter image description here

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

enter image description here

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:

enter image description here

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:

Claims-based authorization in ASP.NET Core | Microsoft Docs

Role based access using client credentials by user4864425

Upvotes: 1

Related Questions