Unnie
Unnie

Reputation: 937

Add application roles as custom claims to Azure AD identities

I have a webapp which supports both form based authentication (using OOTB Asp.net identity framework) and Azure AD based authentication (using OpenID Connect). the authentication works well for both forms based user and Azure AD users. Now the roles are in the database (using OOTB Asp.net identity framework) and the roles are obtained as claims for all the asp.net identity users. But for Azure AD identity users, i am not able to get the role claims. I tried querying the database with email and getting the roles for the Azure AD user and then setting it as the role claim as below:

User.SetClaims(ClaimTypes.Role,roleAdministrator.Name);//calling the set method

Setting the claims as below.

 public static void SetClaims(this IPrincipal user,string claimType,string claimValue)
        {
            if (user?.Identity is ClaimsIdentity claimsIdentity)
            {
                var name = claimsIdentity.FindFirst(claimType);
                if (name != null)
                    claimsIdentity.RemoveClaim(name);
                claimsIdentity.AddClaim(new Claim(claimType, claimValue));
            }
        }

This works only for that particular http request and as soon as I click somewhere else or refresh my page, the role claims are not present in the Azure AD identity anymore.

How can i implement Azure AD auth with roles managed in as asp.net identity roles (and not as Azure AD roles)

Please Note that using a Azure AD roles is not an option for me at this moment, as this is an existing app with asp.net identities and roles. I am trying to add one more auth provider with minimum change. So roles has to be in the database as it is now.

Upvotes: 0

Views: 1222

Answers (1)

Tom Sun
Tom Sun

Reputation: 24549

If we want to add custom attributes for Azure AD user, we could use Directory schema extensions, which can be used to add properties to directory objects without requiring an external data store. You could following this tutorial to register an extension, write and read an extension value.

If Azure AD B2C is possible, you could define custom attributes in Azure Active Directory B2C.

About how to get the custom attributes, please refer to another SO thread.

Upvotes: 0

Related Questions