Azure AD B2C access claim/information from incoming login request - azure-ad-b2c

Currently, using B2C with custom policies having moved from Auth0. It was possible within Auth0 to access the scope claim/property of an incoming login request from the UI and then use that value within Rules to apply some logic. This doesn't seem to be easily do-able in B2C
My user journey allows a user to login using their Azure / Office 365 login via an AD Connector, then enrich the user's claim by calling one of my APIs to get more information about that user account before returning the updated claims to the UI. This all works fine.
What I want to do is expand the enrichment request to include the Audience value from the incoming login request. I have multiple front-end applications that use B2C and want different extra info included in the claims sent back to the UI so filtering on Client ID of the Azure AD APP used by the UI would be good. I would also like to see/access the Scope from the incoming login request as it has some information I would like send to the backend API.
I've tried the following but it doesn't like aud or audience as a claim name and scope is always null.
<TechnicalProfile Id="REST-API">
<DisplayName>Enrich User</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<!-- Set the ServiceUrl with your own REST API endpoint -->
<Item Key="ServiceUrl">https://xxx.mydomain.com/users/b2c</Item>;
<Item Key="SendClaimsIn">Body</Item>
<!-- Set AuthenticationType to Basic or ClientCertificate in production environments -->
<Item Key="AuthenticationType">ApiKeyHeader</Item>
<Item Key="AllowInsecureAuthInProduction">false</Item>
</Metadata>
<CryptographicKeys>
<Key Id="Authorization" StorageReferenceId="B2C_1A_RestApiKey" />
</CryptographicKeys>
<InputClaims>
<!-- Claims sent to your REST API -->
<InputClaim ClaimTypeReferenceId="email" />
<InputClaim ClaimTypeReferenceId="givenName" />
<InputClaim ClaimTypeReferenceId="surname" />
<InputClaim ClaimTypeReferenceId="aud" />
<InputClaim ClaimTypeReferenceId="scope" />
<InputClaim ClaimTypeReferenceId="scp" />
<InputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
</InputClaims>
<OutputClaims>
<!-- Claims parsed from your REST API -->
<OutputClaim ClaimTypeReferenceId="isEnabled" />
<OutputClaim ClaimTypeReferenceId="userId" />
<OutputClaim ClaimTypeReferenceId="accountCode" />
<OutputClaim ClaimTypeReferenceId="role" />
<OutputClaim ClaimTypeReferenceId="env" />
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>

You can get scope with claims resolvers.
Ensure you set the settings.
A more generic way is this.

Related

Any way to provide default values for inputs in an Azure AD B2C custom policy?

I am working on integrating Azure AD B2C into an existing shopping cart application, replacing an existing user identity solution.
I have already created a custom policy to implement user registration / sign-up and integrated it into the normal account creation process. However, I am having a problem with integrating registration during the checkout process.
With the old IDP, the checkout process first collects the user's name and email address. After that has been collected, the user is given the option to create an account with that information (if they are not already logged in). In order to avoid confusing double-entry of the email address, I would like to pass the email address that the user already entered to the B2C sign-up policy and have it fill in the email address input on the form.
Is there any way to do this? I don't find anything like this being addressed in the B2C documentation.
You can use a sign up policy with a claims resolver. Send the email in the query parameter. It’ll prepopulate the email into the text box.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/claim-resolver-overview
Based on the documentation linked by #JasSuri, I was able to come up with a solution.
To implement this, you modify the sign-up technical profile. You must add three things:
Add item IncludeClaimResolvingInClaimsHandling with value true to the metadata
Add a DefaultValue attribute to the email input claim with an appropriate claims resolver notation as the value
Add an AlwaysUseDefaultValue attribute to the email input claim with true as the value
I used an Oauth2 key-value claims resolver (which supports arbitrary query string parameters) and a query parameter named register_email.
The resulting technical profile looks like this:
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">
<DisplayName>Email signup</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="IpAddressClaimReferenceId">IpAddress</Item>
<Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
<Item Key="language.button_continue">Create</Item>
<Item Key="IncludeClaimResolvingInClaimsHandling">true</Item> <!-- ADD THIS -->
</Metadata>
<CryptographicKeys>
<Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" />
</CryptographicKeys>
<InputClaims>
<!-- ADD DefaultValue AND AlwaysUseDefaultValue ATTRIBUTES BELOW -->
<InputClaim ClaimTypeReferenceId="email"
DefaultValue="{OAUTH-KV:register_email}"
AlwaysUseDefaultValue="true" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Verified.Email" Required="true" />
<OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
<OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
<OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" />
<OutputClaim ClaimTypeReferenceId="newUser" />
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonEmail" />
</ValidationTechnicalProfiles>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>

Rest API call in custom policy in Azure AD B2C

I am new and have tried to build custom policy for sign-in by invoking a REST API call to legacy.
The API expects below parameters as input:
client_id=fixed value, client_secret=fixed value, grant_type=fixed value, scope=fixed value, username=variable, password=variable
The above parameters are not for Azure valued but some fixed values that need to be sent in the request.
I have added few portions in the extensions custom policy but seems the request body is not forming correctly and I am getting the error The claims exchange User Migration Via Legacy specified in step '1' returned HTTP error response with Code Bad Request and Reason 'Bad Request'.
What am I doing wrong here? Please help.
Added my portion :
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="RequestBody">
<DisplayName>Request body</DisplayName>
<DataType>string</DataType>
<UserHelpText>RequestBody</UserHelpText>
</ClaimType>
</ClaimsSchema>
<ClaimsTransformations>
<ClaimsTransformation Id="GenerateRequestBody" TransformationMethod="GenerateJson">
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" TransformationClaimType="username" />
<InputClaim ClaimTypeReferenceId="password" TransformationClaimType="password" />
</InputClaims>
<InputParameters>
<InputParameter Id="client_id" DataType="string" Value="client" />
<InputParameter Id="client_secret" DataType="string" Value="sec" />
<InputParameter Id="grant_type" DataType="string" Value="grant" />
<InputParameter Id="scope" DataType="string" Value="scope" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="RequestBody" TransformationClaimType="outputClaim" />
</OutputClaims>
</ClaimsTransformation>
</ClaimsTransformations>
<ClaimsProviders>
<ClaimsProvider>
<DisplayName>REST API to communicate with Legacy IdP</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="UserMigrationViaLegacyIdp">
<DisplayName>REST API call to communicate with Legacy IdP</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
<Item Key="AllowInsecureAuthInProduction">true</Item>
<Item Key="ClaimUsedForRequestPayload">RequestBody</Item>
</Metadata>
<InputClaimsTransformations>
<InputClaimsTransformation ReferenceId="GenerateRequestBody" />
</InputClaimsTransformations>
<InputClaims>
<InputClaim ClaimTypeReferenceId="RequestBody" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="tokenSuccess" DefaultValue="false" />
<OutputClaim ClaimTypeReferenceId="migrationRequired" />
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
Can you share the actual JSON created by the claim transformation? Is it well formatted? You can make troubleshooting easy by displaying the output of <InputClaimsTransformation ReferenceId="GenerateRequestBody" /> before you actually use it as input claim inside the REST API technical profile. This will reveal what's going on with your JSON format.
To do that, first create a self asserted technical profile and add <InputClaimsTransformation ReferenceId="GenerateRequestBody" /> as an output claim transformation to it. Your output claim should be the claim which you will use later in next step in the journey.
In the user journey, add a step that calls the self asserted technical profile. Add next step with App Insights to write the output claim to App Insights( https://learn.microsoft.com/en-us/azure/active-directory-b2c/analytics-with-application-insights)
This will document claim value that REST API is receiving.

Multi tenant Azure B2C Login - how to get external user email address

I am struggling to figure out how to configure Azure B2C for multi-tenant authentication, in particular getting access to the email address of a user that is logging in via an external Azure AD (we're interested in allowing our customers to log in either via a "Local Account" (email address, managed by B2C) or their own Azure AD).
A key part of the issue I am trying to result is the passing of the logged in users email address through to a REST endpoint where our application needs to do some things internally to inject additional application specific claims, which are used later on. Apart from our REST endpoint receiving the email address, everything else is working.
I've got a "Common AAD" technical profile setup like this:
<TechnicalProfile Id="Common-AAD">
<DisplayName>Work Account</DisplayName>
<Description>Login with your Work Account</Description>
<Protocol Name="OpenIdConnect"/>
<Metadata>
<Item Key="METADATA">https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration</Item>
<Item Key="client_id">my_client_id</Item>
<Item Key="response_types">code</Item>
<Item Key="scope">openid email profile</Item>
<Item Key="response_mode">form_post</Item>
<Item Key="HttpBinding">POST</Item>
<Item Key="UsePolicyInRedirectUri">false</Item>
<Item Key="DiscoverMetadataByTokenIssuer">true</Item>
<Item Key="ValidTokenIssuerPrefixes">https://login.microsoftonline.com/</Item>
</Metadata>
<CryptographicKeys>
<Key Id="client_secret" StorageReferenceId="B2C_1A_AADAppSecret"/>
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="oid"/>
<OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid"/>
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name" />
<OutputClaim ClaimTypeReferenceId="surName" PartnerClaimType="family_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" AlwaysUseDefaultValue="true" />
<OutputClaim ClaimTypeReferenceId="identityProvider" PartnerClaimType="iss" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
<OutputClaim ClaimTypeReferenceId="signInName" />
<OutputClaim ClaimTypeReferenceId="otherMails" />
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
<OutputClaim ClaimTypeReferenceId="upn" PartnerClaimType="upn" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin"/>
</TechnicalProfile>
In the orchestration, I am instructing B2C to pass in a bunch of these claims to an application-hosted REST API so that we can do our internal processing:
<TechnicalProfile Id="REST-GetProfile-Dev">
<DisplayName>Do some custom logic</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://the-endpoint.com</Item>
<Item Key="AuthenticationType">None</Item>
<!-- REMOVE the following line in production environments -->
<Item Key="AllowInsecureAuthInProduction">true</Item>
</Metadata>
<InputClaims>
<!-- Claims sent to your REST API -->
<InputClaim ClaimTypeReferenceId="objectId" />
<InputClaim ClaimTypeReferenceId="email" />
<InputClaim ClaimTypeReferenceId="sub" />
<InputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
<InputClaim ClaimTypeReferenceId="userPrincipalName" />
<InputClaim ClaimTypeReferenceId="displayName" />
<InputClaim ClaimTypeReferenceId="otherMails" />
<InputClaim ClaimTypeReferenceId="upnUserName" />
<InputClaim ClaimTypeReferenceId="alternativeSecurityId" />
<InputClaim ClaimTypeReferenceId="upn" />
<InputClaim ClaimTypeReferenceId="signInName" />
<InputClaim ClaimTypeReferenceId="socialIdpUserId" />
<InputClaim ClaimTypeReferenceId="identityProvider" />
<InputClaim ClaimTypeReferenceId="authenticationSource" />
</InputClaims>
<OutputClaims>
<!-- bunch of app specific claims -->
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
However, I can never seem to get an email address, or anything that contains the email address of the logged in user passing through.
I've tried to track through the processing that's defined in the Custom Policy XML files, and it's challenging. To be honest, I've been researching this and have tried adding all kinds of additional claims to outputs from various steps, but it's just not working for me.
Any help in detailing how to get the email address of a user logged in via an external Azure AD passed into a REST orchestration step would be much appreciated.
Thanks.
** Big Edit **
In response to Jas Suri, I have reset everything, applied the changes below as suggested, but am still not seeing this work.
Here's my TrustFrameworkBase.xml:
TrustFrameworkBase.xml
Here's my TrustFrameworkExtensions.xml:
TrustFrameworkExtensions.xml
Here's my Relying Party (SignInSignUpMulti.xml) file:
SignInSignUpMulti.xml
Now, looking at my scenarios:
When I sign in using a "local" account, I see this type of information pass through to my rest endpoint during the user journey:
{
"objectId": "1e91bfba-17a1-43b6-a451-9896fc3c1061",
"signInNames.emailAddress": "email#example.com",
"displayName": "User DispName",
"signInName": "email#example.com",
"authenticationSource": "localAccountAuthentication"
}
That's perfect. I can take this information and gather additional claims to return and all works exactly as I want.
When I sign in as an AD Account that's attached to my org, I get this:
{
"objectId": "a_guid",
"sub": "Not supported currently. Use oid claim.",
"userPrincipalName": "cpim_a_guid#TENANT.onmicrosoft.com",
"displayName": "ThisIs Correct",
"upnUserName": "14218711-5dd1-4a81-8e04-77bd08298aaf",
"alternativeSecurityId": "{\"type\":6,\"identityProvider\":\"https://login.microsoftonline.com/a_guid/v2.0\",\"key\":\"a_key\"}",
"identityProvider": "https://login.microsoftonline.com/a_guid/v2.0",
"authenticationSource": "socialIdpAuthentication"
}
I am missing an email (or the users Sign In) address.
And, the same happens when I try to sign in as an external AD:
{
"objectId": "a_guid",
"sub": "Not supported currently. Use oid claim.",
"userPrincipalName": "cpim_a_guid#TENANT.onmicrosoft.com",
"displayName": "ThisIs Correct",
"upnUserName": "9c865de4-2898-4b18-998b-7fa151f6623d",
"alternativeSecurityId": "{\"type\":6,\"identityProvider\":\"https://login.microsoftonline.com/a_guid/v2.0\",\"key\":\"a_key\"}",
"identityProvider": "https://login.microsoftonline.com/a_guid/v2.0",
"authenticationSource": "socialIdpAuthentication"
}
If I can work out how to pass through the email address or signin address, then I would be extremely happy.
Event during debugging, if I cause the user to be signed in anyway, I inspect the User.Identity, and while I see claims that my rest api is returning during the journey, I still don't have any claim that resembles the email address I am expecting (hoping) to see.
I can definitely work either way - an email address passed to the REST API, or the email address appearing in the final claim set that the application receives.
Any assistance would be much appreciated.
From Azure AD, all users will come back with a unique_name claim, which is the UPN in their Azure AD. You could also rely on this. If you rely on the email claim from AAD, it will only be present if the user has an Exchange Online inbox. You also have to set it up as an optional Azure AD claim in the AAD Multi Tenant App registration.
Usually the UPN and Email are the same in an Azure AD. So in the AAD technical profile, you could add this output claim to capture the AAD UPN:
<OutputClaim ClaimTypeReferenceId="aadUPN" PartnerClaimType="unique_name"/>
Then in the relying party secion, add this output claim:
<OutputClaim ClaimTypeReferenceId="aadUPN" PartnerClaimType="UPNfromAAD"/>

In Azure AD B2C custom policies, how do the IdentityExperienceFrameworkApps connect to AD without secrets

Also posted to https://github.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack/issues/29
In the B2C Custom Policy Starterpack we have the file LocalAccounts/TrustFrameworkExtensions.xml with:
<TechnicalProfiles>
<TechnicalProfile Id="login-NonInteractive">
<Metadata>
<Item Key="client_id">ProxyIdentityExperienceFrameworkAppId</Item>
<Item Key="IdTokenAudience">IdentityExperienceFrameworkAppId</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="client_id" DefaultValue="ProxyIdentityExperienceFrameworkAppID" />
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource" DefaultValue="IdentityExperienceFrameworkAppID" />
</InputClaims>
</TechnicalProfile>
</TechnicalProfiles>
Can someone explain why two applications are required to make these custom policies work?
How does the IEF use each of them?
Besides, I don't see any secret or application key being passed to IEF in these files. How can IEF connect to AAD using Application Ids only?
The login-NonInteractive technical profile authenticates a local account by sending an access token request, using the resource owner password credentials grant type, to your Azure AD directory:
<Metadata>
<Item Key="authorization_endpoint">https://login.microsoftonline.com/{tenant}/oauth2/token</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="grant_type" DefaultValue="password" />
<InputClaim ClaimTypeReferenceId="client_id" DefaultValue="ProxyIdentityExperienceFrameworkAppID" />
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource" DefaultValue="IdentityExperienceFrameworkAppID" />
<InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="username" Required="true" />
<InputClaim ClaimTypeReferenceId="password" Required="true" />
<InputClaim ClaimTypeReferenceId="scope" DefaultValue="openid" />
<InputClaim ClaimTypeReferenceId="nca" PartnerClaimType="nca" DefaultValue="1" />
</InputClaims>
Like all access token requests for an Azure AD directory, this access request must contain the identifier of a client application (i.e. the ProxyIdentityExperienceFramework application) and that of a resource application (i.e. the IdentityExperienceFramework application).
You don't have to specify a secret for the client application because it is registered as a native application.

Can we set custom headers on RESTful API calls in Azure Active Directory B2C custom policies?

I have successfully created an AAD B2C custom policy which makes a call to my application.
Similar to what can be found here:
Integrate REST API claims exchanges in your Azure AD B2C user journey as validation on user input
and here:
Secure your RESTful services using client certificates
<ClaimsProvider>
<DisplayName>XYZ API</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="XYZ">
<DisplayName>XYZ</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://example.com/api/1.0/Users</Item>
<Item Key="AuthenticationType">ClientCertificate</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<CryptographicKeys>
<Key Id="ClientCertificate" StorageReferenceId="B2C_1A_XYZRestClientCertificate" />
</CryptographicKeys>
<InputClaims>
<InputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="givenName" />
<InputClaim ClaimTypeReferenceId="surname" PartnerClaimType="surname" />
<InputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="displayName" />
<InputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="objectId" />
<InputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
<InputClaim ClaimTypeReferenceId="otherMails" PartnerClaimType="otherMails" />
</InputClaims>
<OutputClaims>
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
Our app likes to use custom HTTP headers to track some information about the caller, such as a transaction id. Is it possible to add HTTP headers similar to claims? Something maybe like:
<InputHeaders>
<InputHeader ClaimTypeReferenceId="objectId" HeaderName="transactionId" />
<InputHeader Value="AzureB2C" HeaderName="callerName" />
</InputHeaders>
Right now, it is not possible to split some claims between various places (e.g. body, headers, query string). I suggest you add a request for this feature at the Azure feedback portal for Azure Active Directory.

Resources