page_type | languages | products | name | urlFragment | description | |||
---|---|---|---|---|---|---|---|---|
sample |
|
|
Sign in a user in an ASP.NET Web App with OpenID Connect and the Microsoft identity platform |
AppModelv2-WebApp-OpenIDConnect-DotNet |
This sample demonstrates a ASP.NET Web App application that authenticates users against Azure AD |
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Code of Conduct
This sample demonstrates a ASP.NET web app application that authenticates users against Azure AD.
- The client ASP.NET web app application uses the Microsoft Authentication Library (MSAL) to obtain an ID Token from Azure AD:
- The ID Token proves that the user has successfully authenticated against Azure AD.
- Visual Studio
- An Azure AD tenant. For more information see: How to get an Azure AD tenant
- A user account in your Azure AD tenant.
From your shell or command line:
git clone https://github.com/AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-DotNet.git
cd AppModelv2-WebApp-OpenIDConnect-DotNet
or download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
There is one project in this sample. To register it, you can:
- follow the steps below to manually register your apps
- or use PowerShell scripts that:
- automatically create the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
⚠️ If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.
-
On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory
-
If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
In PowerShell run:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
As a first step you'll need to:
- Sign in to the Azure portal.
- 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 to change your portal session to the desired Azure AD tenant.
- Navigate to the Azure portal and select the Azure AD service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that 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
Quickstart-AspNetWebApp
. - Under Supported account types, select Accounts in this organizational directory only.
- In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI:
https://localhost:44368/
.Note that there are more than one redirect URIs used in this sample. You'll need to add them from the Authentication tab later after the app has been created successfully.
- 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.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select Authentication in the menu.
- If you don't have a platform added, select Add a platform and select the Web option.
- In the Redirect URIs section, enter the following redirect URIs.
https://localhost:44368/signin-oidc
- In Implicit grant section, select the check box for ID tokens.
- In the Logout URL section, set it to
https://localhost:44368/signout-oidc
.
- Select Save to save your changes.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
AppModelv2-WebApp-OpenIDConnect-DotNet\Web.config
file. - Find the key
ClientId
and replace the existing value with the application ID (clientId) of theQuickstart-AspNetWebApp
application copied from the Azure portal. - Find the key
Tenant
and replace the existing value with your Azure AD tenant ID.
For Visual Studio Users
Clean the solution, rebuild the solution, and run it.
-
Open your browser and navigate to
https://localhost:44368
. -
Select the Sign in button on the top right corner. When the user signs-in for the first time , a consent screen is presented with required permissions, select Accept.
Click on See Your Claims link, you will see claims from the signed-in user's token.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Do consider taking a moment to share your experience with us.
-
In
Startup.cs
, Configuration method configures OWIN to use OpenIdConnect as below:public void Configuration(IAppBuilder app) { /// ... OwinTokenAcquirerFactory factory = TokenAcquirerFactory.GetDefaultInstance<OwinTokenAcquirerFactory>(); app.AddMicrosoftIdentityWebApp(factory); factory.Services .Configure<ConfidentialClientApplicationOptions>(options => { options.RedirectUri = "https://localhost:44368/"; }) .AddMicrosoftGraph() .AddInMemoryTokenCaches(); factory.Build(); }
-
HomeController.cs
contains SignIn and SignOut methods as following:public class HomeController : Controller { ... public void SignIn() { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void SignOut() { HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } }
-
ClaimsController
shows how to access the claims in the ID tokenpublic ActionResult Index() { var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity; // You get the user�s first and last name below: ViewBag.Name = userClaims?.FindFirst("name")?.Value; // The subject/ NameIdentifier claim can be used to uniquely identify the user across the web ViewBag.Subject = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value; // TenantId is the unique Tenant Id - which represents an organization in Azure AD ViewBag.TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value; }
-
It also shows how to call Microsoft Graph, with incremental consent (the user will need to consent to more scopes if needed.
// You can also call Microsoft Graph (with incremental consent) try { var me = await this.GetGraphServiceClient().Me.GetAsync(); ViewBag.Username = me.DisplayName; } catch (ServiceException graphEx) when (graphEx.InnerException is MicrosoftIdentityWebChallengeUserException) { HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); return View(); }
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Quickstart: Register an application with the Microsoft identity platform (Preview)
- Understanding Azure AD application consent experiences
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory
azure-ad-b2c
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.