Authenticate users in Blazor Server with Twitch and Azure AD B2C
Tags: security, azure
Published: 2021-04-12 23:25:42

One thing that is awesome about Azure AD B2C is the ability to add any OpenID Connect (OIDC) provider as an authentication provider for your applications. In this blog, we'll go through setting up Twitch (the streaming platform) as an identity option in our Blazor Server web app via Azure AD B2C.

## Set up Twitch for authentication

The first thing we need to do is create an Application in the Twitch portal. This is how we show our intent to use Twitch as an identity provider. Navigate to the [Twitch developer portal](https://dev.twitch.tv/). In the **Applications** tab, let's register a new application:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fh2hz112siupkkh5vt6.png)

Complete the following fields:
-Name: the name of your application (make it something meaningful)
- OAuth Redirect URLs: this should point back to Azure AD B2C where the tokens will be returned. The value should be:
`https://<yourB2CName>.b2clogin.com/<yourB2CName>.onmicrosoft.com/oauth2/authresp`
- Category: choose one of the values that makes sense. I chose Application Integration
- Client ID (autogenerated)
- Client Secret (create a new secret and copy its value)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qphnw0pthr1pymjwt03l.png)

> Note: to create an Application in Twitch, you need to have MFA configured 

The Twitch is done at this point :)

## Configure Twitch as a provider in Azure AD B2C
The next step is to configure Twitch in our B2C tenant so that we can present it as an option during the sign in process. In the Azure AD B2C portal, navigate to the **Identity Providers** tab and select **New Open ID Connect Provider**. In the present form, complete the fields as per below:

- Name: Twitch (the name of the identity provider)
- Metadata url: `https://id.twitch.tv/oauth2/.well-known/openid-configuration`
- Client ID: The client id from your Twitch App
- Client Secret: The client secret from the Twitch App
- Scope: `openid user:read:email`
- Response Type: `code`
- Response Mode: `form_post`
** Identity Provider claims mapping**
- User ID: `sub`
- Display name: `preferred_username`
- Given name: `given_name`
- Surname: `family_name`
- Email: `email`

Make sure to press **Save** in the end

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0zzu9te68fxgq60grrqd.png)

Next, we need to configure one of our **User flows** to use our new identity provider. Navigate to the **User flows** tab and select the flow that your application is or going to use. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcfd759d5v1pj34jzjp0.png)

In the **Identity Providers** tab, select the newly added Twitch OIDC provider:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sljnoy14tay8j3erbatg.png)

If we also want to get the Twitch Access token as part of the authentication process, then there is one extra step. 

We can now run our user flow and test that everything has been configured correctly. In our user flow, we need to navigate to the **Application Claims** and check the **Identity Provider Access Token** checkbox. Make sure to press **Save**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ztsonrt9ilqtyrkveo4.png)

Now, let's see it in action!!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kog4hgqej99cgsugy3t1.gif)

Finally, we need an Azure AD App registration so that our Blazor app can authenticate. In the B2C portal, navigate to the **App Registrations** tab and press the **New Registration**. Type a **Name** and select **Accounts in any identity provider or organizations directory**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjn0xd2s86ijbjynfxuy.png)

In the App Registration, navigate to the **Authentication** tab and press the **Add a platform** button. Select **Web** and enter `https://localhost:5001/signin-oidc` as the Redirect URI. Press **Configure** to persist the changes. In the **Implicit grand and hybrid flows** check both boxes for ID and Access tokens and press **Save**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4esqdswecj2xzlguaww.png)

That's the last change we had to do in B2C. Now, time to write some code...

## Configure Blazor Server to use authenticate with B2C and Twitch

Technically, our Blazor server app doesn't have to know anything about Twitch, since this is an integration that B2C is responsible for. Therefore, from an authentication configuration perspective, our code just needs the B2C bits. Let's get started.

In your favorite shell, type the following:

`dotnet new blazorserver --auth SignleOrgB2C -n BlazorAuthWithTwitch`

Open the `appsetttings.json` file and update the AzureADB2C settings accordingly:

```
{
  "AzureAdB2C": {
    "Instance": "https://<yourB2CName>.b2clogin.com",
    "ClientId": "c77818a3-d610-0000-8da5-de849908425c",
    "CallbackPath": "/signin-oidc",
    "Domain": "<yourB2CName>.onmicrosoft.com",
    "SignedOutCallbackPath": "/signout/b2c_1_susi",
    "SignUpSignInPolicyId": "b2c_1_sisu",
    "ResetPasswordPolicyId": "b2c_1_password_reset",
    "EditProfilePolicyId": "b2c_1_edit_profile"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
```
In `Startup.cs` we need to add a service to get access to the `HttpContext` and therefore the User principal.

In `ConfigureServices()` add the following line:
`services.AddHttpContextAccessor();`

Now we can update one of our views so that we can access the claims principal and get the information we need out of the authenticated user. Open `Index.razor` and paste the following code:

```
@page "/"

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

 <table class="table">
        <thead>
            <tr>
                <th>Key</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>
        @foreach (var claim in @httpContextAccessor.HttpContext.User.Claims)
        {
            <tr>
                <td>@claim.Type</td>
                <td>@claim.Value</td>
            </tr>
        }
    </tbody>
</table>
```
Save and run the Blazor app again. After signing in, you should be presented with the following on the home page :)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1i9h8hsmkuz7m7kkdeif.png)

Mission accomplished! We were able to sign in users to our Blazor Server app via Azure AD B2C using Twitch as one of our identity providers! The nice thing about this set up is that our client application doesn't have to know the details on how to go about acquiring tokens from multiple providers. In a few lines of code (less than 7), I was able to implement authentication in my app and leave the heavy lifting to Azure AD B2C

## Source Code
You can find a fully working solution on this [GitHub repo](https://github.com/425show/BlazorServerAuthWithB2CandTwitch)