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["abcd@hotmail.com"]
                .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

S.Chandra Sekhar
  • 453
  • 3
  • 11
  • 22
  • "salt encryption" can be your solution – Dip Surani Mar 06 '20 at 20:31
  • Could you please provide any sample code or useful links. – S.Chandra Sekhar Mar 07 '20 at 03:06
  • https://www.c-sharpcorner.com/UploadFile/145c93/save-password-using-salted-hashing/ – Dip Surani Mar 07 '20 at 05:34
  • You can change algorithms from SHA1 to according your requirements. Hope this will help – Dip Surani Mar 07 '20 at 05:36
  • 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. – S.Chandra Sekhar Mar 07 '20 at 05:56
  • this stack overflow link will surly help you https://stackoverflow.com/questions/52462796/jwt-how-to-add-custom-claims-and-decode-claims – Dip Surani Mar 07 '20 at 06:51
  • 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. " – S.Chandra Sekhar Mar 31 '20 at 17:35

2 Answers2

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 .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
  • 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. – S.Chandra Sekhar Mar 11 '20 at 01:23
  • That claim is not in access token – Nan Yu Mar 11 '20 at 01:25
  • 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. – S.Chandra Sekhar Mar 11 '20 at 01:41
  • 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 : https://learn.microsoft.com/en-us/graph/extensibility-overview – Nan Yu Mar 11 '20 at 01:49
  • In short , you can update the property using Microsoft Graph ,but you can't make them in access token , – Nan Yu Mar 11 '20 at 01:50
  • 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. – S.Chandra Sekhar Mar 11 '20 at 01:56
  • 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 . – Nan Yu Mar 11 '20 at 02:05
  • Could you provide code samples or any links.It would be a great helpful to me. – S.Chandra Sekhar Mar 11 '20 at 02:30
  • What is the error of `await graphApiClient.Users[employee.EmailAddress] .Request() .UpdateAsync(new User() { AdditionalData = dictionary });` ? directly enter one email instead of `employee.EmailAddress` – Nan Yu Mar 11 '20 at 02:32
  • How to configure aad app manifest to return extension claim and user email adrress in token. – S.Chandra Sekhar Mar 11 '20 at 02:36
  • Use microsoft graph to manage : https://learn.microsoft.com/en-us/graph/extensibility-overview . app manifest doesn't include that . – Nan Yu Mar 11 '20 at 02:41
  • I need to move extension claim attributes provided in access token as given in screenshot to optional claims IDToken right. – S.Chandra Sekhar Mar 11 '20 at 02:45
  • Check this : https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims , but you can't fully customize the attribute . – Nan Yu Mar 11 '20 at 02:53
  • I have tried code as suggested by you but I'm getting error as given in Update 3 in question.Kindly suggest. – S.Chandra Sekhar Mar 11 '20 at 17:08
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

Tony Ju
  • 14,891
  • 3
  • 17
  • 31