简体   繁体   中英

Custom authorization with Azure AD authentication

I am developing a service fabric stateless web application using ASP.NET Core 2.0. This application is using Azure AD to authenticate users from multiple AD tenants. What I want to achieve is using my own role based authorization which can be configured in my application using the authorized user. These roles are stored in my application.

In my current implementation I add authorization to my application by adding a policy with my custom IAuthorizationRequirement . During the authorization of the requirement claims are added based on the users permissions. This means that claims are added post-login. The [Authorize(Roles = "role")] attribute also doesn't work because the role claims are added post-login

What is the correct way to implement this custom authorization which uses the authenticated user from Azure AD?

You can add your own custom claims after the user signs in through the OnTokenValidated event:

.AddOpenIdConnect(o =>
{
    Configuration.GetSection("OpenIdConnect").Bind(o);
    o.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async ctx =>
        {
            string oid = ctx.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");

            var db = ctx.HttpContext.RequestServices.GetRequiredService<AuthorizationDbContext>();

            var objectIdGuid = Guid.Parse(oid);
            bool isSuperAdmin = await db.SuperAdmins.AnyAsync(a => a.ObjectId == objectIdGuid);
            if (isSuperAdmin)
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Role, Roles.SuperAdmin));
                var appIdentity = new ClaimsIdentity(claims, "MyTestAppIdentity");

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

Here as an example we check from a database whether the user is a super admin. Then if they are, we create a new identity for them with the necessary role as a claim.

All the identities are combined on the principal to produce their claim set, so all the other claims will still be available too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM