This article describes how to add authentication for a Twitch account to an Azure AD B2C custom policy.
Architecture
The following diagram illustrates the authentication flow for a Twitch account to an Azure AD B2C custom policy.
The authentication flow requires an Azure function that requests claims for the authenticated user.
For information about Twitch and OAuth 2.0, see https://dev.twitch.tv/docs/authentication.
Prerequisites
- If you don’t already have one, then you must create an Azure AD B2C tenant that is linked to your Azure subscription.
- Prepare your Azure AD B2C tenant by creating the token signing and encryption keys and creating the Identity Experience Framework applications.
- Download one of the starter packs for Azure AD B2C from Microsoft’s GitHub repository.
Create the Azure function
- Create a C# function containing the following code. This implements a GetTwitchCode function that requests claims for the authenticated user. Then publish this C# function to a function app.
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace SignInWithTwitch
{
public static class GetTwitchCode
{
[FunctionName("GetTwitchCode")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest request,
ILogger logger)
{
var redirectUrlBuilder = new StringBuilder("https://id.twitch.tv/oauth2/authorize");
if (!request.QueryString.HasValue)
{
return new BadRequestResult();
}
redirectUrlBuilder.Append(request.QueryString.Value);
var claimsQueryModel = new
{
userinfo = new
{
email = (string) null,
preferred_username = (string) null
}
};
redirectUrlBuilder.Append($"&{HttpUtility.UrlEncode("claims")}={HttpUtility.UrlEncode(JsonConvert.SerializeObject(claimsQueryModel))}");
return new RedirectResult(redirectUrlBuilder.ToString());
}
}
}
Configure a Twitch application
- Log in to https://dev.twitch.tv/console.
- In the Console page, select Register Your Application.
- In the Register Your Application section, enter the following fields and then select Create:
- Name
- OAuth Redirect URLs: Enter either
https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/oauth2/authresp
if you use the built-in domain orhttps://your-domain-name/your-tenant-name.onmicrosoft.com/oauth2/authresp
if you use a custom domain for the Return URL field. Replaceyour-tenant-name
with your tenant name andyour-domain-name
with your custom domain. - Category
- In the Developer Applications section, select Manage for the application registration.
- in the Manage Application section, copy the Client ID field, select New Secret, and then copy the Client Secret field.
Add the client secret for the Twitch application as a policy key
- Sign in to the Azure AD B2C portal.
- Select Identity Experience Framework.
- Select Policy keys.
- Select Add.
- In the Create a key section, enter the following fields and then select Create:
- Options:
Manual
- Name:
TwitchClientSecret
- Secret: Paste the Client Secret field that was copied in the previous section.
- Options:
Configure Twitch as an identity provider
- Open the TrustFrameworkExtensions.xml file.
- Find the ClaimsProviders element. If it doesn’t exist, then add it to the TrustFrameworkPolicy element.
- Add the following ClaimsProvider element to the ClaimsProviders element. Replace
your-twitch-client-id
with the Client ID field that was copied in the Configure a Twitch application section. Replaceyour-function-app-name
with the function app name that was created in the Create the Azure function section.
<ClaimsProvider>
<Domain>twitch.com</Domain>
<DisplayName>Twitch</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Twitch-OAuth2">
<DisplayName>Twitch</DisplayName>
<Protocol Name="OAuth2" />
<Metadata>
<Item Key="client_id">your-twitch-client-id</Item>
<Item Key="authorization_endpoint">https://your-function-app-name.azurewebsites.net/api/GetTwitchCode</Item>
<Item Key="AccessTokenEndpoint">https://id.twitch.tv/oauth2/token</Item>
<Item Key="ClaimsEndpoint">https://id.twitch.tv/oauth2/userinfo</Item>
<Item Key="scope">openid user:read:email</Item>
<Item Key="HttpBinding">POST</Item>
<Item Key="BearerTokenTransmissionMethod">AuthorizationHeader</Item>
<Item Key="UsePolicyInRedirectUri">false</Item>
</Metadata>
<CryptographicKeys>
<Key Id="client_secret" StorageReferenceId="B2C_1A_TwitchClientSecret" />
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" AlwaysUseDefaultValue="true" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="twitch.com" AlwaysUseDefaultValue="true" />
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="sub" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="preferred_username" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
Add a user journey
- Open the TrustFrameworkBase.xml file.
- Copy the UserJourney element that includes
Id="SignUpOrSignIn"
. - Open the TrustFrameworkExtensions.xml file and find the UserJourneys element. If it doesn’t exist, then add it to the TrustFrameworkPolicy element.
- Paste the UserJourney element that was copied in step 2 to the UserJourneys element and replace the Id attribute for this UserJourney element from
"SignUpOrSignIn"
to"TwitchSignUpOrSignIn"
.
Add the identity provider to the user journey
- Add the claims provider that was configured in the Configure Twitch as an identity provider section to the user journey that was added in the previous section.
<OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
<ClaimsProviderSelections>
...
<ClaimsProviderSelection TargetClaimsExchangeId="TwitchExchange" />
</ClaimsProviderSelections>
...
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
...
<ClaimsExchanges>
<ClaimsExchange Id="TwitchExchange" TechnicalProfileReferenceId="Twitch-OAuth2" />
</ClaimsExchanges>
...
</OrchestrationStep>
Configure the relying party policy
- Open the SignUpOrSignIn.xml file.
- Replace the ReferenceId attribute for the DefaultUserJourney element from
"SignUpOrSignIn"
to"
.
SignUpOrSignIn"Twitch
<RelyingParty>
<DefaultUserJourney ReferenceId="TwitchSignUpSignIn" />
...
</RelyingParty>
Upload and test the custom policy
- Upload all policy files in the following order to your Azure AD B2C tenant:
- TrustFrameworkBase.xml
- TrustFrameworkLocalization.xml
- TrustFrameworkExtensions.xml
- SignUpOrSignIn.xml
- Test the B2C_1A_signup_signin policy from your Azure AD B2C tenant.