Skip to content

Latest commit

 

History

History
264 lines (205 loc) · 12.6 KB

AzureADB2B_AuthApp.md

File metadata and controls

264 lines (205 loc) · 12.6 KB
title titleSuffix description services author ms.service ms.subservice ms.topic ms.workload ms.date ms.author ms.custom
Tutorial: Create an ASP.NET Core web app that uses the Microsoft identity platform for authentication | Azure
Microsoft identity platform
In this tutorial, you build an ASP.NET Core web application that uses the Microsoft identity platform for users to signup/signin using their Azure AD or Social identities configured in External Identities blade of your tenant.
active-directory-b2b
Aman
active-directory-b2b-External-Identities
develop
tutorial
identity
08/28/2019
amansi
devx-track-csharp, aaddev, identityplatformtop40

Tutorial: Add Azure AD B2B authentication to an ASP.NET Core web app

In this tutorial, you build an ASP.NET MVC Core web app that signs in users by using the Microsoft identity platform.

When you've completed this guide, your application will be able to accept sign-ups/sign-ins of local Azure AD and social accounts from various social identity providers configured under the external identites blade in your tenant.

In this tutorial:

[!div class="checklist"]

  • Create an ASP.NET Core Web Application project in Visual Studio Code.
  • Add the Microsoft Identity packages.
  • Add code to support user sign-in and sign-out
  • Register the app in the Azure portal
  • Test the app

Prerequisites

How the sample app generated by this guide works

Shows how the sample app generated by this tutorial works

This sample shows how to build a .NET Core MVC Web app that uses OpenID Connect to sign in users in Azure AD tenant.

Libraries

This sample uses Microsoft Identity Web Library, which is a set of ASP.NET Core libraries that simplifies adding authentication and authorization support to web apps and web APIs integrating with the Microsoft identity platform. It provides a single-surface API convenience layer that ties together ASP.NET Core, its authentication middleware, and the Microsoft Authentication Library (MSAL) for .NET. For logging-in purposes, it is sufficient to obtain an ID Token, and the middleware is capable of doing this on its own.

Note: This sample does NOT use MSAL as it only signs-in users (it does not call a Web API). MSAL is used for fetching access for accessing protected APIs (not shown here), as well as ID tokens.

Library Description
Microsoft.Identity.Web The main package. Required by all apps that use Microsoft Identity Web
Microsoft.Identity.Web.UI Adds UI for user sign-in and sign-out and an associated controller for web apps

Set up your project

This section describes how to install and configure the authentication through Microsoft Identity Web Library on an ASP.NET Core project by using OpenID Connect.

Prefer to download this sample's Visual Studio project instead? Download a project and skip to the Register your application to configure the code sample before executing.

Create your ASP.NET project

For ASP.NET Core 3.1, create the app by using WebApp template with the .NET CLI:

  1. Create a folder and rename it to your project name. E.g., C:\Demo\B2C-App
  2. Open elevated command prompt, navigate to the project folder and run below command:
    dotnet new webapp

Add authentication components

In order to add Microsoft Identity Web ASP.NET Core middleware NuGet packages run the following commands:

    dotnet add package Microsoft.Identity.Web
    dotnet add package Microsoft.Identity.Web.UI

About these libraries

These libraries enable single sign-on (SSO) by using OpenID Connect through cookie-based authentication. After authentication is completed and the token representing the user is sent to your application, OWIN middleware creates a session cookie. The browser then uses this cookie on subsequent requests so that the user doesn't have to retype the password, and no additional verification is needed.

Configure the authentication pipeline

The following steps are used to create an Microsoft Identity Web ASP.NET Core middleware Startup class to configure OpenID Connect authentication. This class is executed automatically when your IIS process starts.

  1. Open Visual Studio Code. In addition to existing references, add below references to Startup.cs:

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.Identity.Web;
    using Microsoft.Identity.Web.UI;
  2. In Startup.cs file, update the ConfigureServices method as mentioned below:

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                // Handling SameSite cookie according to https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1
                options.HandleSameSiteCookieCompatibility();
            });
    
            // Sign-in users with the Microsoft identity platform
            services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
    
            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI();
    
            services.AddRazorPages();
        }
  3. Update the Configure method in Startup.cs file with app.UseCookiePolicy(), app.UseAuthentication() and update app.UseEndpoints() as mentioned below:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

More information

The parameters you provide in OpenIDConnectOptions serve as coordinates for the application to communicate with Microsoft identity platform. Because the OpenID Connect middleware uses cookies in the background, you must also set up cookie authentication as the preceding code shows.

Account Controller to handle sign-in and sign-out requests

The AccountController.cs used in this sample is part of Microsoft.Identity.Web.UI NuGet package, and you can find its implementation here. If you want to customize the Sign-in, Sign-up or Sign-out actions, you are encouraged to create your own controller.

Add links to the app's home page for user sign-in and sign-out

In Visual Studio Code, create a new file to add the sign-in/sign-out button and to display user information after authentication:

  1. Right-click the Pages\Shared folder and select New File.

  2. Name the new view _LoginPartial.cshtml.

  3. Add the following HTML, which includes the sign-in/sign-out link, based on whether user is authenticated or not, to the file:

        <ul class="navbar-nav">
            @if (User.Identity.IsAuthenticated)
            {
                    <li class="nav-item">
                        <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
                    </li>
    
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
                    </li>
            }
            else
            {
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
                    </li>
            }
         </ul>
  4. Inject the name of _LoginPartial.cshtml file in the _Layout.cshtml file to display sign-in/sign-out link on home page of the app by adding <partial name="_LoginPartial" /> under <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> as shown below:

        <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
            <ul class="navbar-nav flex-grow-1">
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                </li>
            </ul>
            <partial name="_LoginPartial" />
        </div>

Register your application and add application information to the project:

To register your application, follow these steps:

  1. Go to the new Azure portal - App registrations pane.
  2. Enter a name for your application.
  3. Type https://localhost:5001/signin-oidc as the Redirect URI.
  4. Leave other options as default and click on Register button.

To add application registration information to your project, follow these steps:

  1. In Visual Studio Code, open the appsettings.json file.
  2. Add information about your Azure AD tenant id, domain, application, etc. as shown below:
    {
     "AzureAd": {
       "Instance": "https://login.microsoftonline.com/",
       "Domain": "amansi.onmicrosoft.com",
       "TenantId": "cda8bc2b-0ed0-4b90-8d52-c126c653f508",
       "ClientId": "734229f5-1b52-466f-aa43-b94a15149bd2",
       "CallbackPath": "/signin-oidc",
       "SignedOutCallbackPath ": "/signout-callback-oidc"
     },
     "Logging": {
       "LogLevel": {
         "Default": "Information",
         "Microsoft": "Warning",
         "Microsoft.Hosting.Lifetime": "Information"
       }
     },
     "AllowedHosts": "*"
    }
Property Value
ClientId Application ID of the application registered via Azure portal - App registrations
Domain Domain name of your Azure AD tenant
TenantID Can be found in Azure AD Properties or Overview blade

Test your code

To test your application in Visual Studio Code, press Ctrl+F5 (without debugging) or F5 (with debugging) to run your project. By default, the browser opens to the https://localhost:5001 location.

Note: If it opens to a port other than 5001, make sure the Redirect URI of the application registered via Azure portal - App registrations is updated to that port number.

  1. Click on sign-in link to get redirected to Azure AD authorization endpoint to authenticate and get authorization code.
  2. Click on Signout link to sign out of the application.

Next steps

Learn about calling protected web APIs from web apps with the Microsoft identity platform:

[!div class="nextstepaction"] Web apps calling web APIs