Skip to content

Latest commit

 

History

History
220 lines (142 loc) · 12.6 KB

README.md

File metadata and controls

220 lines (142 loc) · 12.6 KB
services platforms author level client endpoint
active-directory
dotnet
jmprieur
100
ASP.NET Core Web App
Microsoft identity platform

An ASP.NET Core Web app signing-in users with the Microsoft identity platform in your organization

This sample is for Azure AD, not Azure AD B2C. See sample 1-5-B2C, for B2C scenario.

Build status

Scenario

This sample shows how to build a .NET Core MVC Web app that uses OpenID Connect to sign in users. Users can only sign-in with their work and school accounts in their own organization. It leverages the ASP.NET Core OpenID Connect middleware.

Sign in with Azure AD

This is the first chapter of this ASP.NET Core Web App tutorial. Once you understand how to sign-in users in an ASP.NET Core Web App with Open Id Connect, can learn how to enable your Web App to call a Web API on behalf of the signed-in user in a later chapter. You can also sign-in users in any or several Azure Active Directory organizations, and even with Microsoft personal accounts or social identities. For more details the parent directory's Readme.md

How to run this sample

To run this sample:

Pre-requisites: Install .NET Core 3.0 or later (for example for Windows) by following the instructions at .NET and C# - Get Started in 10 Minutes. In addition to developing on Windows, you can develop on Linux, Mac, or Docker.

Step 1: Register the sample with your Azure AD tenant

There is one project in this sample. To register it, you can:

  • either use PowerShell scripts that automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you and modify the Visual Studio projects' configuration files.

    Expand to see how to use this automation
    1. On Windows run PowerShell and navigate to the solution's folder

    2. In PowerShell run:

      Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
    3. Run the script to create your Azure AD application and configure the code of the sample application accordingly

      cd .\AppCreationScripts\ 

    .\Configure.ps1 ```

     > Other ways of running the scripts are described in [App Creation Scripts](./AppCreationScripts/AppCreationScripts.md)
    
    1. Open the Visual Studio solution and click start. That's it!
  • or, if you want to register your application with the Azure portal, follow the steps below:

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Azure AD tenant.

Register the webApp app (WebApp)

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. When the Register an application page appears, enter your application's registration information:

    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example WebApp.

    • In the Supported account types section, select Accounts in this organizational directory only ({tenant name}).

      Expand/collapse screenshot

      Register app

      > Note that there are more than one redirect URIs. You'll need to add them from the **Authentication** tab later after the app has been created successfully.
  4. Select Register to create the application.

  5. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.

    Expand/collapse screenshot

    OVerview page

  6. In the list of pages for the app, select Authentication..

    • In the Redirect URIs section, select Web in the combo-box and enter the following redirect URIs.

      • https://localhost:44321/
      • https://localhost:44321/signin-oidc
    • In the Advanced settings section set Logout URL to https://localhost:44321/signout-oidc

    • In the Advanced settings | Implicit grant section, check ID tokens as this sample requires the ID Token to be enabled to sign-in the user.

      Expand/collapse screenshot

      Authentication page

  7. Select Save.

Note that unless the Web App calls a Web API, no certificate or secret is needed.

Step 2: Download/ Clone this sample code or build the application using a template

This sample was created from the dotnet core 2.2 dotnet new mvc template with SingleOrg authentication, and then tweaked to let it support tokens for the Microsoft identity platform endpoint. You can clone/download this repository or create the sample from the command line:

Option 1: Download/ clone this sample

You can clone this sample from your shell or command line:

git clone https://github.com/Azure-Samples/microsoft-identity-platform-aspnetcore-webapp-tutorial webapp
cd webapp
cd "1-WebApp-OIDC\1-1-MyOrg"

Given that the name of the sample is very long, and so are the name of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

In the appsettings.json file:

  • replace the ClientID value with the Application ID from the application you registered in Application Registration portal on Step 1.
  • replace the TenantId value with the Tenant ID where you registered your Application on Step 1.
  • replace the Domain value with the Azure AD domain name, e.g. contoso.onmicrosoft.com where you registered your Application on Step 1.

Option 2: Create the sample from the command line

  1. Run the following command to create a sample from the command line using the SingleOrg template:

    dotnet new mvc --auth SingleOrg --client-id <Enter_the_Application_Id_here> --tenant-id <yourTenantId> --domain <domainName.onmicrosoft.com>

    Note: Replace Enter_the_Application_Id_here with the Application Id from the application Id you just registered in the Application Registration Portal and <yourTenantId> with the Directory (tenant) ID where you created your application. Specify your actual domain name instead of domainName.onmicrosoft.com

  2. Open the generated project (.csproj) in Visual Studio, and save the solution.

  3. Change the Properties\launchSettings.json file to ensure that you start your web app from https://localhost:44321 as registered. For this:

    • update the sslPort of the iisSettings section to be 44321
    • in the applicationUrl property of use https://localhost:44321
  4. (Optional) If you don't have a custom AccountController to handle the sign-in and sign-out requests, you can use the Microsoft.Identity.Web.UI built-in one. For that, please include this change in Startup.cs:

    • at the top of the file, add the following using directive:

        using Microsoft.Identity.Web.UI;
    • in the ConfigureServices method, change the AddControllersWithView code snippet to this:

        services.AddControllersWithViews(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        }).AddMicrosoftIdentityUI();
    • in Views/Shared/_LoginPartial.cshtml, change the asp-area tag to: asp-area="MicrosoftIdentity"

Step 3: Run the sample

  1. Build the solution and run it.

  2. Open your web browser and make a request to the app. Accept the IIS Express SSL certificate if needed. The app immediately attempts to authenticate you via the identity platform endpoint. Sign in with your personal account or with work or school account.

Troubleshooting

known issue on iOS 12

ASP.NET core applications create session cookies that represent the identity of the caller. Some Safari users using iOS 12 had issues which are described in ASP.NET Core #4467 and the Web kit bugs database Bug 188165 - iOS 12 Safari breaks ASP.NET Core 2.1 OIDC authentication.

If your web site needs to be accessed from users using iOS 12, you probably want to disable the SameSite protection, but also ensure that state changes are protected with CSRF anti-forgery mechanism. See the how to fix section of Microsoft Security Advisory: iOS12 breaks social, WSFed and OIDC logins #4647

Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.

Consider taking a moment to share your experience with us.

About The code

This sample shows how to use the OpenID Connect ASP.NET Core middleware to sign in users from a single Azure AD tenant. The middleware is initialized in the Startup.cs file by passing it the Client ID of the app, and the URL of the Azure AD tenant where the app is registered. These values are read from the appsettings.json file. The middleware takes care of:

  • Downloading the Azure AD metadata, finding the signing keys, and finding the issuer name for the tenant.
  • Processing OpenID Connect sign-in responses by validating the signature and issuer in an incoming JWT, extracting the user's claims, and putting the claims in ClaimsPrincipal.Current.
  • Integrating with the session cookie ASP.NET Core middleware to establish a session for the user.

You can trigger the middleware to send an OpenID Connect sign-in request by decorating a class or method with the [Authorize] attribute or by issuing a challenge (see the AccountController.cs file which is part of ASP.NET Core):

The middleware in this project is created as a part of the open-source ASP.NET Core Security project.

These steps are encapsulated in the Microsoft.Identity.Web library.

Next steps

Learn how to:

Learn more

To understand more about token validation, see