How to set custom claims to aad token using C# code
Asked Answered
S

2

2

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.

Update 1:

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.

Update 2:

I want to use code similar to below for updating custom extension claim attribute present in optional claims of azure ad app but UpdateAsync is not working.

await graphApiClient.Application[clientid]  
            .Request()
            .UpdateAsync(new Application()
            {
                AdditionalData = dictionary
            });

At UpdateAsync(), I'm getting issue as below

Specified HTTP method is not allowed for the request

Kindly let me know the solution to add custom user defined claim to azure ad access token.

Note: Since, I want to update access token ,there will be not be any user info on access token. So, graphApiClient.Users[employee.EmailAddress] won't work, as access token will not have any user info like EmailAddress

I have created extension claim attribute in azure ad ap manifest as below

enter image description here

I want to update extension claim attribute extension_clientid_moviename value dynamically with value obtained from external source through code. How to do that. Kindly suggest.

Update 3:

I have tried below code to update extension claim attribute present in Optional claims ID Token.

   await graphApiServiceClient.Users["[email protected]"]
                .Request()
                .UpdateAsync(new User()
                {
                    AdditionalData = dictionary
                });

I am getting error as below

Code: Request_ResourceNotFound\r\nMessage: Resource '' does not exist or one of its queried reference-property objects are not present.

enter image description here

Schalles answered 6/3, 2020 at 17:51 Comment(7)
"salt encryption" can be your solutionEmbryo
Could you please provide any sample code or useful links.Schalles
c-sharpcorner.com/UploadFile/145c93/…Embryo
You can change algorithms from SHA1 to according your requirements. Hope this will helpEmbryo
Sorry actually I'm bit confused with the Password Encryption Using Salt Hashing approach. I'm not storing any password in database.Could you please explain, how it fits for my requirement. I want to add new custom claims even before generating azure aad jwt token.Schalles
this stack overflow link will surly help you #52463296Embryo
In one of the post AAD Program manager mentioned "Today AAD does not support custom claims from users. It'll be something we wish to make available sometime late this year or early next. "Schalles
P
0

That is because you are using OAuth 2.0 client credentials flow to get access token :

https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow

That flow is commonly used for server-to-server interactions without immediate interaction with a user. So you can't find user information in access token .

The document you provided is adding User's extension property , update that value via Microsoft Graph :

await graphApiClient.Users[employee.EmailAddress]
    .Request()
    .UpdateAsync(new User()
    {
        AdditionalData = dictionary
    });

That email is not from access token , you should manually provide the user's email who the api wants to update the properties value .

But since the property is a User's extension property , you can get the value from claims in ID token when user login with Azure AD in your client app . That claim won't include in access token which issued using client credential flow .

Parrisch answered 9/3, 2020 at 5:31 Comment(14)
I want to update custom user defined claim in access token not ID token. Kindly refer Update 2 in my question for details an suggest for resolution.Schalles
That claim is not in access tokenParrisch
I want to add custom user defined claim to access token. How to do that. I tried by creating extension attribute under optional claims in azure ad app as given in screenshot.But how to update that attribute value dynamically through code.Schalles
1. that extension claim would be include in the ID token not access token . 2. You can use microsoft graph to manage the property of specific user , but you need to grant correct permission : learn.microsoft.com/en-us/graph/extensibility-overviewParrisch
In short , you can update the property using Microsoft Graph ,but you can't make them in access token ,Parrisch
I don't have any ID token having user specific info.I have only access token which has azure ad application data.So, Included extension claim in access token.How can I update extension claim property in absence of User object.Schalles
You don't need to have user object , you just need to provide an email of user in your directory ,for testing manually provide it in code .Parrisch
Could you provide code samples or any links.It would be a great helpful to me.Schalles
What is the error of await graphApiClient.Users[employee.EmailAddress] .Request() .UpdateAsync(new User() { AdditionalData = dictionary }); ? directly enter one email instead of employee.EmailAddressParrisch
How to configure aad app manifest to return extension claim and user email adrress in token.Schalles
Use microsoft graph to manage : learn.microsoft.com/en-us/graph/extensibility-overview . app manifest doesn't include that .Parrisch
I need to move extension claim attributes provided in access token as given in screenshot to optional claims IDToken right.Schalles
Check this : learn.microsoft.com/en-us/azure/active-directory/develop/… , but you can't fully customize the attribute .Parrisch
I have tried code as suggested by you but I'm getting error as given in Update 3 in question.Kindly suggest.Schalles
S
0

Regarding the issue in Update 3, we can not use the guest user email here. We should use ObjectId instead. That's why you got Request_ResourceNotFound error.

await graphApiServiceClient.Users["ObjectId"]
                .Request()
                .UpdateAsync(new User()
                {
                    AdditionalData = dictionary
                });

enter image description here

Schaller answered 27/3, 2020 at 1:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.