| services | platforms | author | level | client | service | endpoint |
|---|---|---|---|---|---|---|
active-directory |
dotnet |
jmprieur |
300 |
ASP.NET Core 2.0 |
ASP.NET Core 2.0 |
AAD V1 |
You expose a Web API and you want to protect it so that only authenticated user can access it.
This sample presents a Web API running on ASP.NET Core 2.0, protected by Azure AD OAuth Bearer Authentication. The Web API is access by an ASP.NET Core 2.0 Web application, in the name of the signed-in user. The ASP.NET Web application uses the OpenID Connect ASP.NET Core middleware and the Active Directory Authentication Library (ADAL.Net) to obtain a JWT access token for the signed-in user through the OAuth 2.0 protocol. The access token is sent to the ASP.NET Core Web API, which authorizes the user using the ASP.NET JWT Bearer Authentication middleware.
For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
This sample been updated to ASP.NET Core 2.0. Looking for previous versions of this code sample? Check out the tags on the ASP.NET Core 1.0 version branch.
The Web API (TodoListService) maintains an in-memory collection of to-do items per authenticated user. Several applications signed-in under the same identity share the to-do list. These can be several instances of the Web App proposed in this sample, but also native clients like the dotnet native (WPF) client as they share the same service.
The ASP.NET Core 2.0 Web application (TodoListWebApp) enables a user to:
- Sign in. The first time a user signs, a consent screen is presented letting him consent for the application accessing the TodoList Service and the Azure Active Directory (so that the Web App can read the user's profile). Because this is a Web App, hosted in a browser, it can be that the user gets immediately signed-in benefiting from Single Sign On with other web applications.
- Click on the Todo List part of the navigation bar of the application. At that point s/he:
- sees the list of to-do items exposed by Web API for the signed-in identity (this list would be empty if the service was just started)
- can add more to-do items (buy clicking on Add item).
- Sign-out
Next time the user navigates to the Web application, s/he is signed-in with the same identity as this identity is persisted in a cookie.

[!Note] If you want to run this sample on Azure Government, navigate to the "Azure Government Deviations" section at the bottom of this page.
- Install .NET Core for Windows by following the instructions at dot.net/core, which will include Visual Studio 2017.
- An Internet connection
- An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, please see How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a Microsoft account (MSA, live account), so if you signed in to the Azure portal with a Microsoft personal account and have never created a user account in your directory before, you need to do that now (See Quickstart: Add new users to Azure Active Directory)
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore.git
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant.
- Sign in to the Azure portal.
- On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where you wish to register your application.
- Click on More Services in the left hand nav, and choose Azure Active Directory.
- Click on App registrations and choose New application registration.
- Enter a friendly Name for the application, for example 'TodoListService' and select 'Web Application and/or Web API' as the Application Type. For the sign-on URL, enter the base URL for the sample, which is by default
https://localhost:44351. Click on Create to create the application. - While still in the Azure portal, choose your application, click on Settings and choose Properties.
- From the Azure portal, note the following information, for instance by copying it to notepad:
- The Tenant domain: See the App ID URI base URL. For example: contoso.onmicrosoft.com
- The Tenant ID: See the Endpoints blade (button next to New application registration). Record the GUID from any of the endpoint URLs. For example: da41245a5-11b3-996c-00a8-4d99re19f292. Alternatively you can also find the Tenant ID in the Properties of the Azure Active Directory object (this is the value of the Directory ID property)
- The Application ID (Client ID): See the Properties blade. For example: ba74781c2-53c2-442a-97c2-3d60re42f403
- If not already done, sign in to the Azure portal.
- On the top bar, click on your account and under the Directory list, choose the same Active Directory tenant as for the service
- Click on More Services in the left hand nav, and choose Azure Active Directory.
- Click on App registrations and choose New application registration.
- Enter a friendly Name for the application, for example 'TodoListWebApp' and select 'Web Application and/or Web API' as the Application Type. For the sign-on URL, enter the base URL for the sample, which is by default
https://localhost:17945/signin-oidc. - While still in the Azure portal, choose your application, click on Settings and choose Properties.
- Find the Application ID value and copy it to the clipboard.
- On the same page, change the
Logout Urlproperty tohttps://localhost:44371/Account/EndSession. This is the default single sign out URL for this sample. - From the Settings menu, choose Keys and add a key - select a key duration of either 1 year or 2 years. When you save this page, the key value will be displayed, copy and save the value in a safe location - you will need this key later to configure the project in Visual Studio - this key value will not be displayed again, nor retrievable by any other means, so please record it as soon as it is visible from the Azure Portal.
- Configure Permissions for your application - in the Settings menu, choose the 'Required permissions' section, click on Add, then Select an API, and type 'TodoListService' in the textbox. Then, click on Select Permissions and select 'Access TodoListService'.
- Open the solution in Visual Studio.
- In the TodoListService project, open the
appsettings.jsonfile. - Find the
Domainproperty and replace the value with your AAD tenant domain, e.g. contoso.onmicrosoft.com. - Find the
TenantIdproperty and replace the value with the Tenant ID you registered earlier (a GUID), - Find the
ClientIdproperty and replace the value with the Application ID (Client ID) property of the TodoListService application, that you registered earlier (also a GUID)
- Open the solution in Visual Studio.
- Open the
appsettings.jsonfile. - In the TodoListWebApp project, open the
appsettings.jsonfile. - Find the
Domainproperty and replace the value with your AAD tenant domain, e.g. contoso.onmicrosoft.com. - Find the
TenantIdproperty and replace the value with the Tenant ID you registered earlier (a GUID), - Find the
ClientIdproperty and replace the value with the Application ID (Client ID) property of the TodoListWebApp application, that you registered earlier (also a GUID) - Find the
ClientSecretand replace the value with the key for the TodoListWebApp that you noted from the Azure portal. - If you changed the base URL of the TodoListWebApp sample, add a
PostLogoutRedirectUriproperty and replace the value with the new base URL of the sample. - Find the
TodoListResourceIdproperty and replace the value with ClientId (Application ID) registered for the TodoListService, (again this is a GUID)
Clean the solution, rebuild the solution, and run it. You might want to go into the solution properties and set both projects as startup projects, with the service project starting first.
When you start the Web API, you will get an empty web page. This is expected.
Explore the sample by signing in into the TodoList Web App, clicking on "Todo List", signing again if needed, adding items to the To Do list, signing-out, and starting again. As explained, if you close the browser tab (or the browser) without signing-out, the next time you run the application you won't be prompted to sign-in again.
NOTE: Remember, the To Do list is stored in memory in this TodoListService sample. Each time you stop the TodoListService API, your To Do list will get emptied.
The code for the service is exactly the same as in the active-directory-dotnet-native-aspnetcore same. Please refer to the readme of that sample to understand how to it was built
The code for the ASP.NET Web App is based on the code of the active-directory-dotnet-webapp-openidconnect-aspnetcore sample. Please read the "About The code" section of that sample first.
Then, based on that code, the following modifications were applied. If you are interested in the details, the following commit details the incremental changes described below:
- Update of the AzureAdOptions class to add a property to compute the
Authorityfrom theinstanceand thetenantID, and adding two other configuration options forClientSecret, theresourceIdof TodoListService (its clientId) and the base address for this service. - Added a
TodoListItemin models to deserialize the Json sent by the TodoListService - Added a
NaiveSessionCacheclass in a new Utils folder which serves as a token cache which livetime is the duration of the session. Updated theStartup.csfile accordingly to add sessions. - Added a
TodoListControllerand aTodoview, as well as a "Todo List" entry in the toolbar of the Web API. This is where most of the interesting code is - Updated the
SignOut()method of theAccountControllerto clear the cache for the user when s/he signs-out. - Updated
AzureAdAuthenticationBuilderExtensions.csto request an authorization code, and redeem it, getting an access token to the Azure AD graph (https://graph.windows.com), so that the token cache contains a token for the user. This token will be used by theTodoControllerto request another token for the TodoListService
In case you were familiar with this scenario in ASP.NET, you'll want to notice the following line in AzureAdAuthenticationBuilderExtensions.cs
options.ResponseType = "id_token code";
indeed, contrary to ASP.NET, ASP.NET Core 2.0 seems to use by default an implicit flow. Without overriding the response type (which by default is id_token), OnTokenValidated event is called instead of OnAuthorizationCodeReceived. In the line above, we request both id_token and code, so that OnTokenValidated is called first which ensures that context.Principal has a non-null value represeting the signed-in user when OnAuthorizeationCodeReceived is called
If you are using Visual Studio 2017
- Edit the TodoListService's properties (right click on
TodoListService.csproj, and choose Properties) - In the Debug tab:
- Check the Launch browser field to
https://localhost:44351/api/todolist - Change the App URL field to be
https://localhost:44351as this is the URL registered in the Azure AD application representing our Web API. - Check the Enable SSL field
- Check the Launch browser field to
The same kind of modifications can be made on the TodoListWebApp.csproj project.
When you deploy this sample to Azure, you will need to:
- update the various URLs (reply URLs, Base URL) in the
appsettings.jsonfiles - Add Reply URLs pointing to the deployed location, for both applications in the Azure portal.
In order to run this sample on Azure Government you can follow through the steps above with a few variations:
- Step 2:
- You must register this sample for your AAD Tenant in Azure Government by following Step 2 above in the Azure Government portal.
- Step 3:
- Before configuring the sample, you must make sure your Visual Studio is connected to Azure Government.
- Navigate to the appsettings.json files for both the TodoListService web API and TodoListWebApp web application. Replace the "Instance" property in the Azure AD section with
https://login.microsoftonline.us/.
Once those changes have been accounted for, you should be able to run this sample on Azure Government.
The scenarios involving Azure Active directory with ASP.NET Core are described in ASP.Net Core | Security | Authentication | Azure Active Directory. From this page, you can access the related samples