|
| 1 | +--- |
| 2 | +title: "Quickstart: Protect an ASP.NET Core web API with the Microsoft identity platform" |
| 3 | +description: In this quickstart, you download and modify a code sample that demonstrates how to protect an ASP.NET Core web API by using the Microsoft identity platform for authorization. |
| 4 | +services: active-directory |
| 5 | +author: Dickson-Mwendia |
| 6 | +manager: CelesteDG |
| 7 | +ms.service: active-directory |
| 8 | +ms.subservice: develop |
| 9 | +ms.topic: portal |
| 10 | +ms.workload: identity |
| 11 | +ms.date: 08/16/2022 |
| 12 | +ROBOTS: NOINDEX |
| 13 | +ms.author: dmwendia |
| 14 | +ms.custom: devx-track-csharp, "scenarios:getting-started", "languages:aspnet-core", mode-api |
| 15 | +#Customer intent: As an application developer, I want to know how to write an ASP.NET Core web API that uses the Microsoft identity platform to authorize API requests from clients. |
| 16 | +--- |
| 17 | + |
| 18 | +# Quickstart: Protect an ASP.NET Core web API with the Microsoft identity platform |
| 19 | + |
| 20 | +> [!div renderon="docs"] |
| 21 | +> Welcome! This probably isn't the page you were expecting. While we work on a fix, this link should take you to the right article: |
| 22 | +> |
| 23 | +> > [Quickstart:Protect an ASP.NET Core web API](web-api-quickstart.md?pivots=devlang-aspnet-core) |
| 24 | +> |
| 25 | +> We apologize for the inconvenience and appreciate your patience while we work to get this resolved. |
| 26 | +
|
| 27 | +> [!div renderon="portal" id="display-on-portal" class="sxs-lookup"] |
| 28 | +> # Quickstart: Protect an ASP.NET Core web API with the Microsoft identity platform |
| 29 | +> |
| 30 | +> In this quickstart, you download an ASP.NET Core web API code sample and review the way it restricts resource access to authorized accounts only. The sample supports authorization of personal Microsoft accounts and accounts in any Azure Active Directory (Azure AD) organization. |
| 31 | +> |
| 32 | +> ## Prerequisites |
| 33 | +> |
| 34 | +> - Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F). |
| 35 | +> - [Azure Active Directory tenant](quickstart-create-new-tenant.md) |
| 36 | +> - [.NET Core SDK 3.1+](https://dotnet.microsoft.com/) |
| 37 | +> - [Visual Studio 2019](https://visualstudio.microsoft.com/vs/) or [Visual Studio Code](https://code.visualstudio.com/) |
| 38 | +> |
| 39 | +> ## Step 1: Register the application |
| 40 | +> |
| 41 | +> First, register the web API in your Azure AD tenant and add a scope by following these steps: |
| 42 | +> |
| 43 | +> 1. Sign in to the [Azure portal](https://portal.azure.com/). |
| 44 | +> 1. If you have access to multiple tenants, use the **Directories + subscriptions** filter :::image type="icon" source="./media/common/portal-directory-subscription-filter.png" border="false"::: in the top menu to switch to the tenant in which you want to register the application. |
| 45 | +> 1. Search for and select **Azure Active Directory**. |
| 46 | +> 1. Under **Manage**, select **App registrations** > **New registration**. |
| 47 | +> 1. For **Name**, enter a name for your application. For example, enter **AspNetCoreWebApi-Quickstart**. Users of your app will see this name, and you can change it later. |
| 48 | +> 1. Select **Register**. |
| 49 | +> 1. Under **Manage**, select **Expose an API** > **Add a scope**. For **Application ID URI**, accept the default by selecting **Save and continue**, and then enter the following details: |
| 50 | +> - **Scope name**: `access_as_user` |
| 51 | +> - **Who can consent?**: **Admins and users** |
| 52 | +> - **Admin consent display name**: `Access AspNetCoreWebApi-Quickstart` |
| 53 | +> - **Admin consent description**: `Allows the app to access AspNetCoreWebApi-Quickstart as the signed-in user.` |
| 54 | +> - **User consent display name**: `Access AspNetCoreWebApi-Quickstart` |
| 55 | +> - **User consent description**: `Allow the application to access AspNetCoreWebApi-Quickstart on your behalf.` |
| 56 | +> - **State**: **Enabled** |
| 57 | +> 1. Select **Add scope** to complete the scope addition. |
| 58 | +> |
| 59 | +> ## Step 2: Download the ASP.NET Core project |
| 60 | +> |
| 61 | +> [Download the ASP.NET Core solution](https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2/archive/aspnetcore3-1.zip) from GitHub. |
| 62 | +> |
| 63 | +> [!INCLUDE [active-directory-develop-path-length-tip](../../../includes/active-directory-develop-path-length-tip.md)] |
| 64 | +> |
| 65 | +> ## Step 3: Configure the ASP.NET Core project |
| 66 | +> |
| 67 | +> In this step, configure the sample code to work with the app registration that you created earlier. |
| 68 | +> |
| 69 | +> 1. Extract the .zip archive into a folder near the root of your drive. For example, extract into *C:\Azure-Samples*. |
| 70 | +> |
| 71 | +> We recommend extracting the archive into a directory near the root of your drive to avoid errors caused by path length limitations on Windows. |
| 72 | +> |
| 73 | +> 1. Open the solution in the *webapi* folder in your code editor. |
| 74 | +> 1. Open the *appsettings.json* file and modify the following code: |
| 75 | +> |
| 76 | +> ```json |
| 77 | +> "ClientId": "Enter_the_Application_Id_here", |
| 78 | +> "TenantId": "Enter_the_Tenant_Info_Here" |
| 79 | +> ``` |
| 80 | +> |
| 81 | +> - Replace `Enter_the_Application_Id_here` with the application (client) ID of the application that you registered in the Azure portal. You can find the application (client) ID on the app's **Overview** page. |
| 82 | +> - Replace `Enter_the_Tenant_Info_Here` with one of the following: |
| 83 | +> - If your application supports **Accounts in this organizational directory only**, replace this value with the directory (tenant) ID (a GUID) or tenant name (for example, `contoso.onmicrosoft.com`). You can find the directory (tenant) ID on the app's **Overview** page. |
| 84 | +> - If your application supports **Accounts in any organizational directory**, replace this value with `organizations`. |
| 85 | +> - If your application supports **All Microsoft account users**, leave this value as `common`. |
| 86 | +> |
| 87 | +> For this quickstart, don't change any other values in the *appsettings.json* file. |
| 88 | +> |
| 89 | +> ## How the sample works |
| 90 | +> |
| 91 | +> The web API receives a token from a client application, and the code in the web API validates the token. This scenario is explained in more detail in [Scenario: Protected web API](scenario-protected-web-api-overview.md). |
| 92 | +> |
| 93 | +> ### Startup class |
| 94 | +> |
| 95 | +> The *Microsoft.AspNetCore.Authentication* middleware uses a `Startup` class that's executed when the hosting process starts. In its `ConfigureServices` method, the `AddMicrosoftIdentityWebApi` extension method provided by *Microsoft.Identity.Web* is called. |
| 96 | +> |
| 97 | +> ```csharp |
| 98 | +> public void ConfigureServices(IServiceCollection services) |
| 99 | +> { |
| 100 | +> services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 101 | +> .AddMicrosoftIdentityWebApi(Configuration, "AzureAd"); |
| 102 | +> } |
| 103 | +> ``` |
| 104 | +> |
| 105 | +> The `AddAuthentication()` method configures the service to add JwtBearer-based authentication. |
| 106 | +> |
| 107 | +> The line that contains `.AddMicrosoftIdentityWebApi` adds the Microsoft identity platform authorization to your web API. It's then configured to validate access tokens issued by the Microsoft identity platform based on the information in the `AzureAD` section of the *appsettings.json* configuration file: |
| 108 | +> |
| 109 | +> | *appsettings.json* key | Description | |
| 110 | +> |------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| |
| 111 | +> | `ClientId` | Application (client) ID of the application registered in the Azure portal. | |
| 112 | +> | `Instance` | Security token service (STS) endpoint for the user to authenticate. This value is typically `https://login.microsoftonline.com/`, indicating the Azure public cloud. | |
| 113 | +> | `TenantId` | Name of your tenant or its tenant ID (a GUID), or `common` to sign in users with work or school accounts or Microsoft personal accounts. | |
| 114 | +> |
| 115 | +> The `Configure()` method contains two important methods, `app.UseAuthentication()` and `app.UseAuthorization()`, that enable their named functionality: |
| 116 | +> |
| 117 | +> ```csharp |
| 118 | +> // The runtime calls this method. Use this method to configure the HTTP request pipeline. |
| 119 | +> public void Configure(IApplicationBuilder app, IHostingEnvironment env) |
| 120 | +> { |
| 121 | +> // more code |
| 122 | +> app.UseAuthentication(); |
| 123 | +> app.UseAuthorization(); |
| 124 | +> // more code |
| 125 | +> } |
| 126 | +> ``` |
| 127 | +> |
| 128 | +> ### Protecting a controller, a controller's method, or a Razor page |
| 129 | +> |
| 130 | +> You can protect a controller or controller methods by using the `[Authorize]` attribute. This attribute restricts access to the controller or methods by allowing only authenticated users. An authentication challenge can be started to access the controller if the user isn't authenticated. |
| 131 | +> |
| 132 | +> ```csharp |
| 133 | +> namespace webapi.Controllers |
| 134 | +> { |
| 135 | +> [Authorize] |
| 136 | +> [ApiController] |
| 137 | +> [Route("[controller]")] |
| 138 | +> public class WeatherForecastController : ControllerBase |
| 139 | +> ``` |
| 140 | +> |
| 141 | +> ### Validation of scope in the controller |
| 142 | +> |
| 143 | +> The code in the API verifies that the required scopes are in the token by using `HttpContext.VerifyUserHasAnyAcceptedScope> (scopeRequiredByApi);`: |
| 144 | +> |
| 145 | +> ```csharp |
| 146 | +> namespace webapi.Controllers |
| 147 | +> { |
| 148 | +> [Authorize] |
| 149 | +> [ApiController] |
| 150 | +> [Route("[controller]")] |
| 151 | +> public class WeatherForecastController : ControllerBase |
| 152 | +> { |
| 153 | +> // The web API will only accept tokens 1) for users, and 2) having the "access_as_user" scope for this API |
| 154 | +> static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" }; |
| 155 | +> |
| 156 | +> [HttpGet] |
| 157 | +> public IEnumerable<WeatherForecast> Get() |
| 158 | +> { |
| 159 | +> HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); |
| 160 | +> |
| 161 | +> // some code here |
| 162 | +> } |
| 163 | +> } |
| 164 | +> } |
| 165 | +> ``` |
| 166 | +> |
| 167 | +> [!INCLUDE [Help and support](../../../includes/active-directory-develop-help-support-include.md)] |
| 168 | +> |
| 169 | +> ## Next steps |
| 170 | +> |
| 171 | +> The GitHub repository that contains this ASP.NET Core web API code sample includes instructions and more code samples that show you how to: |
| 172 | +> |
| 173 | +> - Add authentication to a new ASP.NET Core web API. |
| 174 | +> - Call the web API from a desktop application. |
| 175 | +> - Call downstream APIs like Microsoft Graph and other Microsoft APIs. |
| 176 | +> |
| 177 | +> > [!div class="nextstepaction"] |
| 178 | +> > [ASP.NET Core web API tutorials on GitHub](https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2) |
0 commit comments