page_type | languages | products | name | urlFragment | description | ||||
---|---|---|---|---|---|---|---|---|---|
sample |
|
|
Call Microsoft Graph on behalf-of the signed-in users in your Blazor Server Application |
ms-identity-blazor-server |
This sample demonstrates how to call Microsoft Graph on behalf-of the signed-in users in your Blazor Server Application |
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- Deployment
- More information
- Community Help and Support
- Contributing
- Code of Conduct
This sample demonstrates an ASP.NET Core Blazor Server application that authenticates users with Azure Active Directory (Azure AD). It then acquires an Access Token for Microsoft Graph and calls the Microsoft Graph API.
- The client ASP.NET Core Blazor Server application uses the Microsoft Authentication Library MSAL.Net and Microsoft.Identity.Web libraries to obtain an Access Token from Azure AD.
- The client application acquires an Access Token for Microsoft Graph.
- The Access Token is used as a bearer token to authorize the user to call the Microsoft Graph API
- Microsoft Graph API responds with the resource that the user has access to.
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- An Azure AD tenant. For more information see: How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a personal Microsoft account. Therefore, if you signed in to the Azure portal with a personal account and have never created a user account in your directory before, you need to do that now.
From your shell or command line:
cd ms-identity-blazor-server\WebApp-graph-user\Call-MSGraph
⚠️ 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 for manually register your apps
- or use PowerShell scripts that:
- automatically creates 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
-
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
WebApp-blazor-server
. - 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:44318/
.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:44318/signin-oidc
- In the Logout URL section, set it to
https://localhost:44318/signout-oidc
.
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret
), - Select one of the available key durations (In 1 year, In 2 years, or Never Expires) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy the generated value for use in the steps later.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Select the Add a permission button and then,
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select the User.Read in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- 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
appsettings.json
file. - Find the key
ClientId
and replace the existing value with the application ID (clientId) of theWebApp-blazor-server
application copied from the Azure portal. - Find the key
TenantId
and replace the existing value with your Azure AD tenant ID. - Find the key
Domain
and replace the existing value with your Azure AD tenant name. - Find the app key
ClientSecret
and replace the existing value with the key you saved during the creation of theWebApp-blazor-server
app, in the Azure portal.
You can run the sample by using either Visual Studio or command line interface as shown below:
Clean the solution, rebuild the solution, and run it.
cd blazorserver-calls-MS-graph
dotnet restore
dotnet dev-certs https --clean
dotnet dev-certs https --trust
Learn more about HTTPS in .NET Core.
In the console window execute the below command:
dotnet run
-
Open your browser and navigate to
https://localhost:44318
. -
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.
You will see claims from the signed-in user's token.
-
Select Profile from navigation bar on the left. If user has signed-in then information fetched from Microsoft Graph is displayed, otherwise login screen will appear.
ℹ️ 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
, add below lines of code in ConfigureServices method:services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi")) .AddInMemoryTokenCaches();
This enables your application to use the Microsoft identity platform endpoint to sign-in users and to call Microsoft Graph API.
-
Index.razor is the landing page when application starts. Index.razor contains child component called
UserClaims
. If user is authenticated successfully,UserClaims
displays a few claims present in the ID Token issued by Azure AD. -
In the
UserClaimsBase.cs
class, GetClaimsPrincipalData method retrieves signed-in user's claims using the GetAuthenticationStateAsync() method of the AuthenticationStateProvider class.public class UserClaimsBase : ComponentBase { [Inject] private AuthenticationStateProvider AuthenticationStateProvider { get; set; } protected string _authMessage; protected IEnumerable<Claim> _claims = Enumerable.Empty<Claim>(); private string[] printClaims = { "name", "preferred_username", "tid", "oid" }; protected override async Task OnInitializedAsync() { await GetClaimsPrincipalData(); } private async Task GetClaimsPrincipalData() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { _authMessage = $"{user.Identity.Name} is authenticated."; _claims = user.Claims.Where(x => printClaims.Contains(x.Type)); } else { _authMessage = "The user is NOT authenticated."; } } }
-
UserProfile.razor component displays user information retrieved by GetUserProfile method of UserProfileBase.cs.
UserProfileBase.cs
calls Microsoft Graph/me
endpoint to retrieve user information.public class UserProfileBase : ComponentBase { [Inject] GraphServiceClient GraphClient { get; set; } [Inject] MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler { get; set; } protected User _user = new User(); protected override async Task OnInitializedAsync() { await GetUserProfile(); } private async Task GetUserProfile() { try { var request = GraphClient.Me.Request(); _user = await request.GetAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); ConsentHandler.HandleException(ex); } } }
Refer to the Azure deployment guide to deploy this sample code to an Azure App Service.
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Quickstart: Register an application with the Microsoft identity platform (Preview)
- Quickstart: Configure a client application to access web APIs (Preview)
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
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.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
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.