You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
title: "Quickstart: Sign in users and call the Microsoft Graph API from an ASP.NET Core web app"
3
-
description: Learn how an ASP.NET Core web app leverages Microsoft.Identity.Web to implement Microsoft sign-in using OpenID Connect and call Microsoft Graph
3
+
description: Learn how an ASP.NET Core web app uses Microsoft.Identity.Web to implement Microsoft sign-in using OpenID Connect and call Microsoft Graph
# Quickstart: Sign in users and call the Microsoft Graph API from an ASP.NET Core web app
22
22
23
-
The following quickstart uses a ASP.NET Core web app code sample to demonstrate how to sign in users from any Azure Active Directory (Azure AD) organization.
24
23
25
-
See [How the sample works](#how-the-sample-works) for an illustration.
24
+
This quickstart uses a sample ASP.NET Core web app to show you how to sign in users by using the [authorization code flow](./v2-oauth2-auth-code-flow.md) and call the Microsoft Graph API. The sample uses [Microsoft Authentication Library for .NET](/entra/msal/dotnet/) and [Microsoft Identity Web](/entra/msal/dotnet/microsoft-identity-web/) for ASP.NET to handle authentication.
25
+
26
+
In this article you register a web application in the Microsoft Entra admin center, and download a sample ASP.NET web application. You'll run the sample application, sign in with your personal Microsoft account or a work or school account, and sign out.
26
27
27
28
## Prerequisites
28
29
29
-
*[Visual Studio 2022](https://visualstudio.microsoft.com/vs/) or [Visual Studio Code](https://code.visualstudio.com/)
30
+
*An Azure account with an active subscription. If you don't already have one, [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
## Register the application in the Microsoft Entra admin center
37
35
38
-
1. Sign in to the [Azure portal](https://portal.azure.com).
39
-
1. If access to multiple tenants is available, 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 to register the application.
40
-
1. Search for and select **Azure Active Directory**.
41
-
1. Under **Manage**, select **App registrations** > **New registration**.
42
-
1. For **Name**, enter a name for the application. For example, enter **AspNetCore-Quickstart**. Users of the app will see this name, and can be changed later.
43
-
1. Set the **Redirect URI** type to **Web** and value to `https://localhost:44321/signin-oidc`.
36
+
1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) as at least an [Cloud Application Administrator](../roles/permissions-reference.md#cloud-application-administrator).
37
+
1. Browse to **Identity** > **Applications** > **App registrations**.
38
+
1. On the page that appears, select **+ New registration**.
39
+
1. When the **Register an application** page appears, enter a name for your application, such as *identity-client-app*.
40
+
1. Under **Supported account types**, select *Accounts in this organizational directory only*.
44
41
1. Select **Register**.
45
-
1. Under **Manage**, select **Authentication**.
46
-
1. For **Front-channel logout URL**, enter **https://localhost:44321/signout-oidc**.
47
-
1. Under **Implicit grant and hybrid flows**, select **ID tokens**.
1. Enter a **Description**, for example `clientsecret1`.
51
-
1. Select **In 1 year** for the secret's expiration.
52
-
1. Select **Add** and immediately record the secret's **Value** for use in a later step. The secret value is *never displayed again* and is irretrievable by any other means. Record it in a secure location as you would any password.
53
-
54
-
### Step 2: Download the ASP.NET Core project
55
-
56
-
[Download the ASP.NET Core solution](https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/archive/aspnetcore3-1-callsgraph.zip)
57
-
58
-
### Step 3: Configure your ASP.NET Core project
59
-
60
-
1. Extract the *.zip* file to a local folder that's close to the root of the disk to avoid errors caused by path length limitations on Windows. For example, extract to *C:\Azure-Samples*.
61
-
1. Open the solution in the chosen code editor.
62
-
1. In *appsettings.json*, replace the values of `ClientId`, and `TenantId`. The value for the application (client) ID and the directory (tenant) ID, can be found in the app's **Overview** page on the Azure portal.
63
-
64
-
```json
65
-
"Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
66
-
"ClientId": "Enter_the_Application_Id_here",
67
-
"TenantId": "common",
68
-
```
69
-
70
-
-`Enter_the_Application_Id_Here` is the application (client) ID for the registered application.
71
-
- Replace `Enter_the_Tenant_Info_Here` with one of the following:
72
-
- If the 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`). The directory (tenant) ID can be found on the app's **Overview** page.
73
-
- If the application supports **Accounts in any organizational directory**, replace this value with `organizations`.
74
-
- If the application supports **All Microsoft account users**, leave this value as `common`.
75
-
- Replace `Enter_the_Client_Secret_Here` with the **Client secret** that was created and recorded in an earlier step.
76
-
77
-
For this quickstart, don't change any other values in the *appsettings.json* file.
78
-
79
-
### Step 4: Build and run the application
42
+
1. The application's **Overview** pane displays upon successful registration. Record the **Application (client) ID** and **Directory (tenant) ID** to be used in your application source code.
80
43
81
-
Build and run the app in Visual Studio by selecting the **Debug** menu > **Start Debugging**, or by pressing the F5 key.
44
+
## Add a redirect URI
82
45
83
-
A prompt for credentials will appear, and then a request for consent to the permissions that the app requires. Select **Accept** on the consent prompt.
84
-
85
-
:::image type="content" source="media/quickstart-v2-aspnet-core-webapp/webapp-01-consent.png" alt-text="Screenshot of the consent dialog box, showing the permissions that the app is requesting from the user.":::
86
-
87
-
After consenting to the requested permissions, the app displays that sign-in has been successful using correct Azure Active Directory credentials. The user's account email address will be displayed in the *API result* section of the page. This was extracted using the Microsoft Graph API.
88
-
89
-
:::image type="content" source="media/quickstart-v2-aspnet-core-webapp-calls-graph/webapp-02-signed-in.png" alt-text="Screenshot of the web browser displaying the running web app and the user signed in.":::
90
-
91
-
## More information
92
-
93
-
This section gives an overview of the code required to sign in users and call the Microsoft Graph API on their behalf. This overview can be useful to understand how the code works, main arguments, and also if you want to add sign-in to an existing ASP.NET Core application and call Microsoft Graph. It uses [Microsoft.Identity.Web](microsoft-identity-web.md), which is a wrapper around [MSAL.NET](msal-overview.md).
94
-
95
-
### How the sample works
96
-
97
-

98
-
99
-
### Startup class
100
-
101
-
The *Microsoft.AspNetCore.Authentication* middleware uses a `Startup` class that's executed when the hosting process starts:
102
-
103
-
```csharp
104
-
// Get the scopes from the configuration (appsettings.json)
To obtain the sample application, you can either clone it from GitHub or download it as a *.zip* file.
55
+
-[Download the .zip file](https://github.com/Azure-Samples/ms-identity-docs-code-dotnet/archive/refs/heads/main.zip). Extract it to a file path where the length of the name is fewer than 260 characters.
56
+
- To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:
// Enables a UI and controller for sign in and sign out.
130
-
services.AddRazorPages()
131
-
.AddMicrosoftIdentityUI();
132
-
}
133
-
```
62
+
## Create and upload a self-signed certificate
134
63
135
-
The `AddAuthentication()` method configures the service to add cookie-based authentication. This authentication is used in browser scenarios and to set the challenge to OpenID Connect.
64
+
1. Using your terminal, use the following commands to navigate to create a self-signed certificate in the project directory.
136
65
137
-
The line that contains `.AddMicrosoftIdentityWebApp` adds Microsoft identity platform authentication to the application. The application is then configured to sign in users based on the following information in the `AzureAD` section of the *appsettings.json* configuration file:
|`ClientId`| Application (client) ID of the application registered in the Azure portal. |
142
-
|`Instance`| Security token service (STS) endpoint for the user to authenticate. This value is typically `https://login.microsoftonline.com/`, indicating the Azure public cloud. |
143
-
|`TenantId`| Name of your tenant or the tenant ID (a GUID), or `common` to sign in users with work or school accounts or Microsoft personal accounts. |
71
+
1. Return to the Microsoft Entra admin center, and under **Manage**, select **Certificates & secrets** > **Upload certificate**.
72
+
1. Select the **Certificates (0)** tab, then select **Upload certificate**.
73
+
1. An **Upload certificate** pane appears. Use the icon to navigate to the certificate file you created in the previous step, and select **Open**.
74
+
1. Enter a description for the certificate, for example *Certificate for aspnet-web-app*, and select **Add**.
75
+
1. Record the **Thumbprint** value for use in the next step.
144
76
145
-
The `EnableTokenAcquisitionToCallDownstreamApi` method enables the application to acquire a token to call protected web APIs. `AddMicrosoftGraph` enables the controllers or Razor pages to benefit directly the `GraphServiceClient` (by dependency injection) and the `AddInMemoryTokenCaches` methods enables your app to benefit from a token cache.
77
+
## Configure the project
146
78
147
-
The `Configure()` method contains two important methods, `app.UseAuthentication()` and `app.UseAuthorization()`, that enable their named functionality. Also in the `Configure()` method, you must register Microsoft Identity Web routes with at least one call to `endpoints.MapControllerRoute()` or a call to `endpoints.MapControllers()`:
79
+
1. In your IDE, open the project folder, *ms-identity-docs-code-dotnet\web-app-aspnet*, containing the sample.
80
+
1. Open *appsettings.json* and replace the file contents with the following snippet;
* `TenantId` - The identifier of the tenant where the application is registered. Replace the text in quotes with the `Directory (tenant) ID` that was recorded earlier from the overview page of the registered application.
85
+
* `ClientId` - The identifier of the application, also referred to as the client. Replace the text in quotes with the `Application (client) ID` value that was recorded earlier from the overview page of the registered application.
86
+
* `ClientCertificates` - A self-signed certificate is used for authentication in the application. Replace the text of the `CertificateThumbprint` with the thumbprint of the certificate that was previously recorded.
161
87
162
-
### Protect a controller or a controller's method
88
+
## Run the application and sign in
163
89
164
-
The controller or its methods can be protected by applying the `[Authorize]` attribute to the controller's class or one or more of its methods. This `[Authorize]` attribute restricts access by allowing only authenticated users. If the user isn't already authenticated, an authentication challenge can be started to access the controller. In this quickstart, the scopes are read from the configuration file:
90
+
1. In your project directory, use the terminal to enter the following command;
1. Copy the `https` URL that appears in the terminal, for example, `https://localhost:5001`, and paste it into a browser. We recommend using a private or incognito browser session.
97
+
1. Follow the steps and enter the necessary details to sign in with your Microsoft account. You'll be requested an email address so a one time passcode can be sent to you. Enter the code when prompted.
98
+
1. The application will request permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select **Accept**.
99
+
1. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
176
100
177
-
[!INCLUDE [Help and support](includes/error-handling-and-tips/help-support-include.md)]
101
+

178
102
179
-
## Next steps
103
+
## Sign-out from the application
180
104
181
-
The following GitHub repository contains the ASP.NET Core code sample referenced in this quickstart and more samples that show how to achieve the following:
105
+
1. Find the **Sign out** link in the top right corner of the page, and select it.
106
+
1. You'll be prompted to pick an account to sign out from. Select the account you used to sign in.
107
+
1. A message appears indicating that you have signed out.
108
+
1. Although you have signed out, the application is still running from your terminal. To stop the application in your terminal, press **Ctrl+C**.
182
109
183
-
- Add authentication to a new ASP.NET Core web application.
184
-
- Call Microsoft Graph, other Microsoft APIs, or your own web APIs.
185
-
- Add authorization.
186
-
- Sign in users in national clouds or with social identities.
110
+
## Related content
187
111
188
-
> [!div class="nextstepaction"]
189
-
> [ASP.NET Core web app tutorials on GitHub](https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/)
112
+
- [Quickstart: Protect an ASP.NET Core web API with the Microsoft identity platform](./quickstart-web-api-aspnet-core-protect-api.md).
113
+
- Create an ASP.NET web app from scratch with the series [Tutorial: Register an application with the Microsoft identity platform](./web-app-tutorial-01-register-application.md).
0 commit comments