How to set custom claims to aad token using C# code

Jhon 1 Reputation point
2020-03-07T14:36:00.84+00:00

I have a webapi which generates aad token and I have written token generation logic in Get() method in webapi.

I'm able generate aad jwt token from webapi get() method but, now I want to include some custom claims into the token.

How can I set custom claims to aad token using c#.

I have used below code for generating aad token.

var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["TenantID"].ToString());  
            var credential = new ClientCredential(clientId: ConfigurationManager.AppSettings["ClientID"].ToString(), clientSecret: secret);  
            var result = await authenticationContext.AcquireTokenAsync(  
                ConfigurationManager.AppSettings["Resource"].ToString(),  
                credential  
                ).ConfigureAwait(false);  

Kindly share any sample c# code to set custom claims to aad token generated from above code .

Note: I want to set a new custom claim for aad token where custom claim value obtained from external logic.

Looks like below post may be useful.

https://www.rahulpnath.com/blog/azure-ad-custom-attributes-and-optional-claims-from-an-asp-dot-net-application/

I tried below following above post.

Generated jwt token to call Graph API. But I got blocked at below code.

   var dictionary = new Dictionary<string, object>();  
        dictionary.Add(employeeCodePropertyName, employee.Code);  
  
//Here I can't use graphApiClient.Users because, I don't have any user info on my jwt token. It will be just Access token which as details related to aad application.I want to update extension attribute which is present in OptionalClaims -> Access Token of AAD Application Manifest.  
        await graphApiClient.Users[employee.EmailAddress]    
            .Request()  
            .UpdateAsync(new User()  
            {  
                AdditionalData = dictionary  
            });  

How to update extension claim attribute present in access token of optional claims . I want to update through c# code. How to do that. Kindly suggest.

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,229 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Marilee Turscak-MSFT 36,891 Reputation points Microsoft Employee
    2020-03-12T22:50:29.727+00:00

    I saw that someone answered you on Stackoverflow, but this similar answer may also be helpful. https://stackoverflow.com/questions/47326180/asp-net-core-how-to-add-claims-to-user/47346567

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.