0

i have questions. Im using azure ad for my front end and backend. Front end using angular. The FE will connect to azure AD and pass the token to our api. Our api will validate the token from FE.then i will check the user email from azure ad. If user not exist in our database. I will add a new one to my db. So right now i dont want to use role management inside the azure ad. It is possible i issue another token by my own instead of using the azure ad? The problem is, when i want to authorize my api using role table in my db. I cant simply [Authorize("Admin")] because this one will check the roles claims inside azure token. I want to use my roles in my db instead. So other solution i can think is create custom authorize attribute but this might not best solution because it will search the user role in db every request. So now if someone have experience like my problem feel free to give ur suggestion. Thank you

1 Answers1

1

Check this thread, you can add custom claims in OnTokenValidated of OIDC event:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));


services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {


            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});

Then, you could create Claims-based authorization or Policy-based authorization, and you could also create Custom Authorization attributes to do the Authentication.

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • okay thank you, i already find another solution at here, need do some tweak also. https://stackoverflow.com/questions/49694383/use-multiple-jwt-bearer-authentication https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-5.0 – muhammad ammar Jun 22 '21 at 14:28