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 Work or School accounts or Microsoft personal accounts
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.
This sample shows how to build an ASP.NET Core 2.2 MVC Web app that uses OpenID Connect to sign in users. Users can use either their personal accounts (including outlook.com, live.com, and others) as well as their work and school accounts. Thw work and school accounts are usually from an organization that has an Azure Active Directory tenant. It leverages the ASP.NET Core OpenID Connect middleware.
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 your own Azure Active Directory organizations, any organization and even with social identities. For more details the parent directory's Readme.md
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.
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. If you want to use this automation:
-
On Windows run PowerShell and navigate to the solution's folder
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the following script to create and configure your Azure AD application and configure the code of the sample application as well.
.\AppCreationScripts\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts
- Once you've run the script, please ensure that you've followed the following manual steps. Azure AD PowerShell does not yet create an app whose audience is
Work or School + personal accounts
. This audience setting is only possible from the Azure portal as of today: - Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
- If your account is present in more than one Azure AD tenant, select
Directory + Subscription
at the top right corner in the menu on top of the page, and switch your portal session to the desired Azure AD tenant. - Navigate to the Microsoft identity platform for developers App registrations page.
and locate your newly created app in the list.
Tip: If you register your apps with the the provided Poweshell scripts, you can navigate directly to the app registration portal page of your newly created app, using links provided in the AppCreationScripts\createdApps.html. This file is generated by the scripts during the app registration and configuration process.
- Select the Manifest section for your app.
- Search for signInAudience and make sure it's set to AzureADandPersonalMicrosoftAccount
"signInUrl": null, "signInAudience": "AzureADandPersonalMicrosoftAccount",
-
-
Click Save to save the app manifest.
-
Open the Visual Studio solution and click start. That's it!
- or, if you don't want to use automation, follow the steps below:
As a first step you'll need to:
- Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
- 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.
- Navigate to the Microsoft identity platform for developers App registrations page.
- Select New registration.
- 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 any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
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.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- 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.
- 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.
- In the Redirect URIs section, select Web in the combo-box and enter the following redirect URIs.
- Select Save.
Note that unless the Web App calls a Web API, no certificate or secret is needed.
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:
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-3-AnyOrgOrPersonal"
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"common"
-
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 common
Note: Replace
Enter_the_Application_Id_here
with the Application Id from the application Id you just registered in the Application Registration Portal. -
Open the generated project (.csproj) in Visual Studio, and save the solution.
-
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. -
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 theMicrosoft.Identity.Web
project) -
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.
- 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 theiisSettings
section to be44321
- in the
applicationUrl
property of usehttps://localhost:44321
-
-
Build the solution and run it.
-
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 Microsoft identity platform endpoint. Sign in with your personal account or with work or school account.
By default, when you use the dotnet core template with SingleOrg
authentication option and follow the instructions in this guide to configure the application to use the Microsoft identity platform endpoint, both personal accounts - like outlook.com, live.com, and others - as well as Work or school accounts from any organizations that are integrated with Azure AD can sign in to your application. These multi-tenant apps are typically used on SaaS applications.
It's possible to restric the audience for your application by changing the audience in your application registration.
Note that, using the same application resgistration you've done, you can also restrict the accounts types that can sign in to your application, by using one of these options:
Open appsettings.json and replace the line containing the TenantId
value with organizations
:
"TenantId": "organizations",
You can also learn from the 1. WebApp signs-in users with Microsoft Identity (OIDC) / in any org/ step of the tutorial if you are interested in this use case. You will also learn how to restrict to this multi-tenant application to specific tenants.
Open appsettings.json and replace the line containing the TenantId
value with consumers
:
"TenantId": "consumers",
You can restrict sign-in access for your application to only user accounts that are in a single Azure AD tenant - including guest accounts of that tenant. This scenario is a common for line-of-business applications:
-
Open appsettings.json and replace the line containing the
TenantId
value with the domain of your tenant, for example, contoso.onmicrosoft.com or the guid for the Tenant ID:"TenantId": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com or the Tenant Id]",
You can also learn from the 1. WebApp signs-in users with Microsoft Identity (OIDC) / in my org/ step of the tutorial if you are interested in this use case
See restrict restrict users from specific organizations to sign-in to your web app
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.
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
Learn how to:
To understand more about token validation, see
To understand more about app registration, see:
- Quickstart: Register an application with the Microsoft identity platform (Preview)
- Quickstart: Configure a client application to access web APIs (Preview)
- enable your organization only or any Microsoft accounts to sign-in to your Web app
- restrict restrict users from specific organizations to sign-in to your web app