Nico
Nico

Reputation: 13830

How do I use Azure AD authentication with SQL based role management in AspNet Core 3?

I can't find any documentation, I'm guessing because Azure AD Application roled are beeing pushed heavily by Microsoft. What I need is AzureAD for auth and DB based role. Ideally using RoleManager, but custom role management would work also.

Main reasons I can't use application roles: don't have the licence, don't have any admin access to target tenant.

Upvotes: 0

Views: 71

Answers (1)

Samuele Cozzi
Samuele Cozzi

Reputation: 73

I have found somewhere on StackOverflow an answer, but now I can't find it again

My implementation consists in adding this code in Sartup.cs -> ConfigureServices

    // AD configuration
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => { Configuration.Bind("AzureAd", options); });

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    //... Some code

    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            string oid = ctx.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
            string name = ctx.Principal.Identity.Name;
            var db = ctx.HttpContext.RequestServices.GetRequiredService<IdentityContext>();

            var objectIdGuid = Guid.Parse(oid);

            var authorizedUsers = //Some code with db...;

            if (authorizedUsers.Contains(name))
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Role, "MyRole"));
                var appIdentity = new ClaimsIdentity(claims, "MyAppIdentity");

                ctx.Principal.AddIdentity(appIdentity);
            }
        }
    };
    /...

I hope this piece of code can help you

Upvotes: 1

Related Questions