i am trying to have both grant-type in oAuth 2.0. because i need to setup some of my API methods need use client credentials since those are used in service to service connection and for some others i need to setup Authorization grant-type since it was used as user to service connection. my oAuth token provider was Azure Identity service and API was build in .NET Core
Asked
Active
Viewed 301 times
0
-
when you used Azure Identity service to protect your web api, whatever the grant type you want to use, you all need to generate access token for the api. And when you want to use client credentials grant-type, you the token will contain the claim `roles`, and for Authorization grant-type, token will contain `scp`. so you can set different `authorize` attribute for different methods. `[Authorize(Roles = "access_as_application")]` for `roles` and `[RequiredScope(scopeRequiredByApi)]` for `scp`. – Tiny Wang Jan 19 '23 at 09:02
-
related document: https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-verification-scope-app-roles?tabs=aspnetcore – Tiny Wang Jan 19 '23 at 09:02
1 Answers
0
This is possible by creating two different clients. In both cases the clients will manage authentication according to their flow, then get an access token with which to call the API. The API owner should also design scopes that clients request.
The API's first job should be to validate a JWT access token on every request. You could use the Microsoft middleware to do this:
private void ConfigureOAuth(IServiceCollection services)
{
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = this.configuration.MetadataEndpoint;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "myissuer",
ValidAudience = "myaudience"
};
});
}
Your API controllers will then receive a ClaimsPrincipal
with which you implement authorization. You can use authorization policies for this, to check you have the right scopes and claims for the current operation:
[HttpGet("{id}/transactions")]
[Authorize(Policy = "mypolicy")]
public async Task<Transactions> GetTransactionsAsync(string id)
{
// Implementation goes here
}

Gary Archer
- 22,534
- 2
- 12
- 24