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

纵然是瞬间 提交于 2020-04-17 19:10:52

问题


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

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.


回答1:


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

https://docs.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 .




回答2:


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
                });



来源:https://stackoverflow.com/questions/60569243/how-to-set-custom-claims-to-aad-token-using-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!