Step by Step securing Applications with AAD B2C and EasyAuth

Today I show you step by step how you can use Azure Active Directory Business to Consumer (AAD B2C) to secure your backend site/services.

For that reason I create a service backend and two web applications:

  • REST Backend-Service (Web-API) secured by AADB2C
  • Single Page Application
  • ASP.NET Application

Both applications will be able to access the web-api after the user is authenticated. The following diagram illustrates our example:

Create the Infrastructure

First of all we will create our required infrastructure:

  • AAD B2C Instance in Azure
  • 3 Azure Web Apps

Setup the Azure Web Apps

  1. Login to https://portal.azure.com
  2. Create a new resource group (f.e. "b2ctest")
  3. Add 3 Web Apps to this resource group
SPA-App Web-API ASP.NET Core App
Name b2cspaspec* b2ctestspecapi* b2ctestspec*
Runtime Node 12 (LTS) .NET Core 3.1 .NET Core 3.1
Plan YourFreePlan-1 YourFreePlan-1 YourFreePlan-1
https://b2cspaspec.azurewebsites.net/ https://b2ctestspecapi.azurewebsites.net/ https://b2ctestspec.azurewebsites.net/

*) These names are already taken, choose unique names!

  1. Configure Git-Deployment for the SPA-App
    • Select the web app in the azure portal
    • Under Deployment** – Deployment Center
      • Select CI / Local Git and click Continue
      • Select "App Service build service" and click Continue
      • Finish
Git-Clone Url https://b2cspaspec.scm.azurewebsites.net:443/b2cspaspec.git
Username $b2cspaspec
Password av********cs

Copy the Git Clone URL and store the git credentials

Setup Azure AAD B2C Tenant

Next we will create a new Azure Active Directory B2C Tenant. You can skip that step if you already have one.

  1. Login to https://portal.azure.com
  2. Create a new ressource group for your AAD B2C
  3. Add an Azure Active Directory B2C instance (Settings should be obvious)
    • Organization Name
    • Initial Domain name
    • Country/Region
  4. To access your AAD B2C Tenant you need to switch to that tenant like you would switch to another AAD tenant. (Upper right corner)

Create User Flows in AAD B2C

Navigate to the AAD B2C Overview page

Select New user flow under Policies / UserFlows to select a predefined user flow. We select Sign up and sign in in the recommended version. This will allow a potential user to sign up and in, or an existing user to sign in.

Configure the flow as so:

  • Name: B2C_1_ (f.e. signupin ==> B2C_1_signupin)
  • Identity Provider: Select "Email signup"
  • MFA: SMS or phone
  • MFA Enforcement: Conditional
  • Check Conditional Access option
  • Select additional attributes to be collected

Click CREATE to create the flow. Under User Flows select your flow again and click on Properties as we want to modify the password complexity.

I choose the following settings, but you can obviously choose different:

  • Complexity: Custom
  • Character set: All
  • Minimum length: 16
  • Maximum length: 80
  • Character classes required: None

Create Application registrations in AAD B2C

Each of our services (2 webapps and 1 webapi) need to be secured and therefore represented as AAD applications in our B2C tenant.

Again navigate to the AAD B2C Overview page and select App registrations

Register AAD-App Web-API

  • Name: b2ctestspecapi

  • Supported account type: Accounts in any identity provider or organizational directory (for authenticating users with user flows)

  • Redirect URI: Webhttps://b2ctestspecapi.azurewebsites.net/.auth/login/aad/callback (Enter you WebApp URI there and append /.auth/login/aad/callback which will be the path EasyAuth of Azure App Service will require!)

  • Under Overview note the Application (Client) ID (af9c********0f66 in my case)

  • Under Manage / Authentication / Implicit Grant

    • Check "Access Tokens"
    • Check "ID Tokens"
  • Under Manage / Certificates & secrets / Client Secrets

    • Create a new secret and keep it (-Ox********** in my case)
  • Under Manage / API permissions add following permissions (Do not forget to GRANT CONSENT afterwards)

    • offline_access (Delegated)
    • openid (Delegated)
    • Grant admin consent for your tenant
  • Under Manage / Expose an API

Register AAD-App ASP.NET Core App

  • Name: b2ctestspec

  • Supported account type: Accounts in any identity provider or organizational directory (for authenticating users with user flows)

  • Redirect URI: Webhttps://b2ctestspec.azurewebsites.net/.auth/login/aad/callback (Enter you WebApp URI there and append /.auth/login/aad/callback which will be the path EasyAuth of Azure App Service will require!)

  • Under Overview note the Application (Client) ID (cf6d********d2ee in my case)

  • Under Manage / Authentication / Implicit Grant

    • Check "Access Tokens"
    • Check "ID Tokens"
  • Under Manage / Certificates & secrets / Client Secrets

    • Create a new secret and keep it (.dSz********** in my case)
  • Under Manage / API permissions add following permissions if not present(Do not forget to GRANT CONSENT afterwards)

    • offline_access (Delegated)
    • openid (Delegated)
    • From My Apis select b2ctestspecapi (app we created earlier) and add both permissions:
      • Spec.Read
      • Spec.Write
    • Grant admin consent for your tenant

Register AAD-App SPA-App

  • Name: spademo

  • Supported account type: Accounts in any identity provider or organizational directory (for authenticating users with user flows)

  • Redirect URI: Single-page application SPAhttps://b2cspaspec.azurewebsites.net/ (We will use MSAL here)

  • Under Overview note the Application (Client) ID (9192********fe5 in my case)

  • Under Manage / Authentication / Platform Configurations

  • Under Manage / Authentication / Implicit Grant

    • Check "Access Tokens"
    • Check "ID Tokens"
  • Under Manage / API permissions add following permissions if not present(Do not forget to GRANT CONSENT afterwards)

    • offline_access (Delegated)
    • openid (Delegated)
    • From My Apis select b2ctestspecapi (app we created earlier) and add both permissions:
      • Spec.Read
      • Spec.Write
    • Grant admin consent for your tenant

Test User Flow and create Test-User

Again navigate to the AAD B2C Overview page and select B2C_1_signupin policy under Policies/User Flows. Click on the Run user flow button and select the spademo application. As reply url choose https://jwt.ms so we can examine the result. Select no access token ressources now. Click Run user flow

You should see a SignIn/SignUp Dialog – Create a new user with one of your EMail-Addresses. Once you hit create you should be redirected to https://jwt.ms where you can examine you Auth-Token.

Secure Web-API and ASP.NET Core App with Azure App Easy Auth

Since the best security code is the code you never write, we want to make use of Azure Apps Easy Auth service to protect our ASP.NET Core App and Service.

For this switch back into your regular tenant (where the Azure Apps are located). To view all App Services in your tenant click this link.

Secure B2CTestSpecAPI AppService

First we configure EasyAuth for our API app service. Then we create a simple api application that we deploy there.

Navigate to your b2ctestspecapi App Service.

Under Settings – Authentication/Authorization enable App Service Authentication. Also enable the Token Store (at the end of the page). Select Login with Azure Active Directory as action. This will ensure that no unauthenticated call is reaching your application.

Select Azure Active Directory from the list of Authentication Providers Under the Managment Mode click on Advanced

  • ClientId: af9c************0f66
  • Issuer URL: https://yourtenantname.b2clogin.com/yourtenantname.onmicrosoft.com/B2C_1_signupin/v2.0/.well-known/openid-configuration (We had this url from the Endpoints if you remember)
  • Client Secret: .-OX*************

Create a simple ASP.NET Core App AADDemoAPI in Visual Studio which automatically will have the WeatherForeCast API implemented. Deploy this service to this Azure App Service.

Test the authentication by navigating to https://b2ctestspecapi.azurewebsites.net which should require a login. Once you have logged in you should be able to examine the tokens by accessing: https://b2ctestspecapi.azurewebsites.net/.auth/me

Secure B2CTestSpec AppService

Navigate to your b2ctestspec App Service.

Under Settings – Authentication/Authorization enable App Service Authentication. Also enable the Token Store (at the end of the page). Select Login with Azure Active Directory as action. This will ensure that no unauthenticated call is reaching your application. If you want to serve some pages without authenticating choose the other option. In this case however you need to check in you code if you are authenticated or not! If not you have to make sure to redirect the user to the login page.

Select Azure Active Directory from the list of Authentication Providers Under the Managment Mode click on Advanced

  • ClientId: cf6d************a2ee
  • Issuer URL: https://yourtenantname.b2clogin.com/yourtenantname.onmicrosoft.com/B2C_1_signupin/v2.0/.well-known/openid-configuration (We had this url from the Endpoints if you remember)
  • Client Secret: .dSz*************
  • Allowed Token Audiences:

This should do the trick right? Well as long as we want only to authenticate this will work. But if we also want the access token to access our WebAPI we need to do more.

Right no configuration in the UI where you can specify the required permission scopes. To request the scopes you have to redirect users to this url:

There is however a workaround to this i stumbled upon in the documentation. Using the mangement API you can set the default scopes for EasyAuth. If you want to use an UI to do that use https://ressources.azure.com and navigate to subscriptions/yoursubscription/resourceGroups/yourResourceGroup/providers/Microsoft.Web/sites/yourSite/config/authsettings. Under the entry allowedaudiences add:

  • resource: Client ID of the WebAPI you want to call
  • scope: add webservices scopes to openid, offline access
"additionalLoginParams": [
	  "resource=af9c************0f66",
	  "scope=openid offline_access https://spectologicb2crtm.onmicrosoft.com/specapi/Spec.Read https://spectologicb2crtm.onmicrosoft.com/specapi/Spec.Write"
	]

Let’s now implement an ASP.NET Core Application that we can deploy to this Azure App Service and will call the API webservice we created earlier.

In Visual Studio 2019 create a new ASP.NET Core MVC app named AADDemoWF and implement the Index-Method of HomeController.cs

public async Task Index()
{
    ViewData["X-MS-TOKEN-AAD-ID-TOKEN"] = Request.Headers["X-MS-TOKEN-AAD-ID-TOKEN"];
    ViewData["X-MS-TOKEN-AAD-ACCESS-TOKEN"] = Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"];
    ViewData["X-MS-TOKEN-AAD-EXPIRES-ON"] = Request.Headers["X-MS-TOKEN-AAD-EXPIRES-ON"];
    ViewData["X-MS-TOKEN-AAD-REFRESH-TOKEN"] = Request.Headers["X-MS-TOKEN-AAD-REFRESH-TOKEN"];
 
    string accessToken = Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"];
    try
    {
        string url = "https://b2ctestspecapi.azurewebsites.net/weatherforecast";
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
        request.Headers.Add("Authorization", $"Bearer {accessToken}");
        var response = await _client.SendAsync(request);
        ViewData["SERVICERESP"] = await response.Content.ReadAsStringAsync();
 
    }
    catch (Exception ex)
    {
        ViewData["SERVICERESP"] = ex.ToString();
    }
    return View();
}

Also adapt the index.cshtml page to visualize the tokens and the service response.

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
<h1 class="display-4">Auth Tokens</h1>
<div>X-MS-TOKEN-AAD-ID-TOKEN</div><br />
<div>X-MS-TOKEN-AAD-ACCESS-TOKEN</div><br />
<div>X-MS-TOKEN-AAD-EXPIRES-ON</div><br />
<div>X-MS-TOKEN-AAD-REFRESH-TOKEN</div><br />
<div>SERVICERESP</div><br />

<a href="https://b2ctestspec.azurewebsites.net/.auth/login/aad?p=&post_login_redict_uri=/&scope=openid+offline_access+https%3A%2F%2Fspectologicb2crtm.onmicrosoft.com%2Fspecapi%2FSpec.Read&redirect_uri=https%3A%2F%2Fb2ctestspec.azurewebsites.net%2F">Explicit</a>
</div>

Deploy this application to the App Service and you should be able to access this site after logging in through AAD B2

Secure the SPA Application

In this case I am using a sample provided by microsoft that we will adapt to our requirements. Open a terminal and clone the sample of microsoft.

First we will change app/authConfig.js. If you do not request all required resource permission scopes during login the silet token aquiring will fail and fall back to a authentication that will show a brief popup. Since the user is logged on already this will just result in a brief flicker. To avoid this we add all base scopes in the initial login.

// Config object to be passed to Msal on creation.
// For a full list of msal.js configuration parameters, 
// visit https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md

const msalConfig = {
    auth: {
        clientId: "9192**************0fe5",
        authority: "https://spectologicb2crtm.b2clogin.com/spectologicb2crtm.onmicrosoft.com/B2C_1_signupin",
        knownAuthorities: [ 'spectologicb2crtm.b2clogin.com' ],
        redirectUri: "https://b2cspaspec.azurewebsites.net/",
    },
    ... 

// Add here the scopes that you would like the user to consent during sign-in
const loginRequest = {
    scopes: ["openid","offline_access","https://spectologicb2crtm.onmicrosoft.com/specapi/Spec.Read"]
};
 
// Add here the scopes to request when obtaining an access token for MS Graph API
const tokenRequest = {
    scopes: ["User.Read", "Mail.Read"],
    forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};
 
const weatherTokenRequest = {
    scopes: ["https://spectologicb2crtm.onmicrosoft.com/specapi/Spec.Read"],
    forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};

Change app/graphConfig.js and add weatherConfig there:

// Add here the endpoints for MS Graph API services you would like to use.
const graphConfig = {
    graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
    graphMailEndpoint: "https://graph.microsoft.com/v1.0/me/messages",
};
...
// Add here the endpoints for Weather services you would like to use.
const weatherConfig = {
    weatherEndpoint: "https://b2ctestspecapi.azurewebsites.net/weatherforecast"
};

Add a function callWeatherAPI to app/graph.js. The code just makes a request to an given endpoint with a bearertoken.

function callWeatherAPI(endpoint, token, callback) {
    console.log(endpoint);
    console.log(token);
    const headers = new Headers();
    const bearer = `Bearer ${token}`;
 
    headers.append("Authorization", bearer);
 
    const options = {
        method: "GET",
        headers: headers
    };
 
    console.log('request made to Weather API at: ' + new Date().toString());
 
    fetch(endpoint, options)
        .then(response => response.json())
        .then(response => callback(response, endpoint))
        .catch(error => console.log(error));
}

Change app/authPopup.js and adapt the seeProfile-Method that is called once a user clicks on the Profile-Button

...
function seeProfile() {
    getTokenPopup(weatherTokenRequest).then(response => {
        callWeatherAPI(
            weatherConfig.weatherEndpoint, 
            response.accessToken, 
            updateUI);
    }).catch(error => {
        console.error(error);
    });
}
...

The upper method will call updateUI-function after a successful call to the webservice. We change the implementation in app/ui.js

...
function updateUI(data, endpoint) {
    console.log('Graph API responded at: ' + new Date().toString());
 
    if (endpoint === weatherConfig.weatherEndpoint) {
        const dataElement = document.createElement('p');
        dataElement.innerHTML = "<strong>Data: </strong>" + JSON.stringify(data);
        profileDiv.appendChild(dataElement);
    } else if (endpoint === graphConfig.graphMeEndpoint) {
        const title = document.createElement('p');
...

We are almost done now. We need to change Server.js to serve the right port for Azure App Service:

// app.listen(port); Replace this line with the next
app.listen(process.env.PORT||port);

Check in all changes to master in this git repository!

Now deploy our git repository to our NODE Azure App Service by using the credentials we created earlier.

Now you can try your service at https://b2cspaspec.azurewebsites.net/

That’s it for today! Have a great day!

AndiP

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Google Foto

Du kommentierst mit Deinem Google-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s