Skip to content

Latest commit

 

History

History
214 lines (152 loc) · 9.83 KB

File metadata and controls

214 lines (152 loc) · 9.83 KB
page_type languages products name urlFragment description
sample
csharp
aspnet-core
azure-active-directory
azure-web-apps
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

Call Microsoft Graph on behalf-of the signed-in users in your Blazor Server Application

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. About the code
  10. Next chapter of the tutorial: the Web app calls Web API
  11. Deployment
  12. More information
  13. Community Help and Support
  14. Contributing
  15. Code of Conduct

.NET Core

Overview

In the second chapter, we extend our ASP.NET Core Blazor Server application to call a downstream API Microsoft Graph to obtain more information about the signed-in user.

Scenario

Continuing from the previous chapter of the tutorial, this chapter adds the following steps:

  1. The client application acquires an Access Tokens for Microsoft Graph.
  2. The Access Token is used as a bearer token to authorize the user to call the Microsoft Graph API
  3. Microsoft Graph API responds with the resource that the user has access to.

Overview

How to run this sample

In the downloaded folder

From your shell or command line:

cd ms-identity-blazor-server\WebApp-graph-user\Call-MSGraph

Update the Registration for the sample application(s) with your Azure Active Directory tenant

Update Registration for the web app (WebApp-blazor-server)

  1. In App registrations page, find the WebApp-blazor-server app.
  2. 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.
  3. 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.
  4. 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.

Configure the web app (WebApp-blazor-server)

Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.

  1. Open blazorserver-calls-MS-graph\appsettings.json file and copy the keys from "AzureAd" section of previous chapter's WebApp-OIDC\MyOrg\blazorserver-singleOrg\appsettings.json file.
  2. Find the app key ClientSecret and replace the existing value with the key you saved during the creation of the WebApp-blazor-server app, in the Azure portal.

Running the sample

You can run the sample by using either Visual Studio or command line interface as shown below:

Run the sample using Visual Studio

Clean the solution, rebuild the solution, and run it.

Run the sample using a command line interface such as VS Code integrated terminal

Step 1. Install .NET Core dependencies

cd blazorserver-calls-MS-graph
dotnet restore

Step 2. Trust development certificates

dotnet dev-certs https --clean
dotnet dev-certs https --trust

Learn more about HTTPS in .NET Core.

Step 3. Run the applications

In the console window execute the below command:

dotnet run

Explore the sample

  1. Open your browser and navigate to https://localhost:44318.

  2. Select the Sign in button on the top right corner. You will see claims from the signed-in user's token.

    UserClaims

  3. 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.

    UserProfile

ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.

We'd love your feedback!

Were we successful in addressing your learning objective? Do consider taking a moment to share your experience with us.

About the code

For details about the code to enable your Blazor Server application to sign-in users, see About the code section, of the README.md file located at WebApp-OIDC/MyOrg.

This section, here, is only about the additional code added to let the Web App call the Microsoft Graph.

  1. 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.

  2. 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);
            }
        }
    }

Next chapter of the tutorial: the Web app calls Web API

Navigate to the chapter Secure and call a Web API with the Microsoft identity platform to learn about securing and calling Web APIs.

Deployment

Refer to the Azure deployment guide to deploy this sample code to an Azure App Service.

More information

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

Community Help and Support

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.

Contributing

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.