EasyAuthForK8s/OCP.Msal.Proxy.Web
Jon Lester 3885c8ef7e Fix url rewrite for ingress rule
Added url rewrite to handle redirect to the MicrosoftIdentity controller
2021-10-08 15:23:46 -04:00
..
AppCreationScripts initial commit 2019-11-17 23:56:07 -05:00
Controllers Fix url rewrite for ingress rule 2021-10-08 15:23:46 -04:00
Models Refactoring to net5.0 2021-10-05 14:34:32 -04:00
.dockerignore initial commit 2019-11-17 23:56:07 -05:00
.gitignore initial commit 2019-11-17 23:56:07 -05:00
OCP.Msal.Proxy.Web.csproj Refactoring to net5.0 2021-10-05 14:34:32 -04:00
Program.cs initial commit 2019-11-17 23:56:07 -05:00
README.md initial commit 2019-11-17 23:56:07 -05:00
Startup.cs Fix url rewrite for ingress rule 2021-10-08 15:23:46 -04:00
appsettings.Development.json initial commit 2019-11-17 23:56:07 -05:00
appsettings.json Refactoring 2020-01-29 16:36:49 -05:00
sample.json initial commit 2019-11-17 23:56:07 -05:00

README.md

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 active-directory-b2c-dotnetcore-webapp, until we incorporate the B2C variation in the tutorial.

Build status

Scenario

This sample shows how to build a .NET Core 2.2 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 2.2 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

      .\AppCreationScripts\Configure.ps1
      

      Other ways of running the scripts are described in App Creation Scripts

    4. 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 succesfully.
  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 Implicit grant flow 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>
    

    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.

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

  3. Add the Microsoft.Identity.Web.csproj project which is located at the root of this sample repo, to your solution (Add Existing Project ...). It's used to simplify signing-in and, in the next tutorial phases, to get a token

  4. Add a reference from your newly generated project to Microsoft.Identity.Web (right click on the Dependencies node under your new project, and choose Add Reference ..., and then in the projects tab find the Microsoft.Identity.Web project)

  5. Open the Startup.cs file and:

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

       using Microsoft.Identity.Web;
      
    • in the ConfigureServices method, replace the two following lines:

       services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
               .AddAzureAD(options => Configuration.Bind("AzureAd", options));
      

      by this line:

       services.AddMicrosoftIdentityPlatformAuthentication(Configuration);
      

      This enables your application to use the Microsoft identity platform endpoint. This endpoint is capable of signing-in users both with their Work and School and Microsoft Personal accounts.

    1. 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

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.

Toubleshooting

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 mecanism. 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.

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 project, and in particular in the StartupHelper.cs file

Next steps

Learn how to:

Learn more

To understand more about token validation, see