Skip to content

A React & Redux single-page application that authorizes an ASP.NET Core web API to call MS Graph API on its behalf

License

Notifications You must be signed in to change notification settings

YohanSciubukgian/ms-identity-javascript-react-spa-dotnetcore-webapi-obo

 
 

Repository files navigation

page_type languages products description urlFragment
sample
javascript
csharp
azure-active-directory
microsoft-authentication-library
dotnet-core
react
redux
This sample demonstrates a React & Redux single-page application authorizing an ASP.NET Core Web API to call MS Graph API on its behalf using the MS Graph SDK
ms-identity-javascript-react-spa-dotnetcore-webapi-obo

A React & Redux single-page application authorizing an ASP.NET Core Web API to call MS Graph API on behalf of a signed-in user

Overview

This sample demonstrates a React & Redux single-page application which lets a user authenticate and then obtain an access token to call an ASP.NET Core Web API, protected by Azure AD. The Web API then calls the MS Graph API on the user's behalf using the on-behalf-of flow.

The Web APIs call to MS Graph API is made using the MS Graph SDK.

Scenario

  • The sample implements an onboarding scenario where a profile is created for a new user whose fields are pre-populated by the available information about the user on MS Graph API.
  • The ProfileSPA uses MSAL.js to authenticate a user and React-Redux to store id and access tokens. (:warning: this is for demonstration purposes only -in production, you should never store sensitive information in your Redux store)
  • Once the user authenticates, ProfileSPA obtains an access token from Azure Active Directory (Azure AD).
  • The access token is then used to authorize the ProfileAPI to call MS Graph API on user's behalf. In order to call MS Graph API, ProfileAPI uses the MS Graph SDK.
  • To protect its endpoint and accept only the authorized calls, the ProfileAPI uses MSAL.NET and Microsoft.Identity.Web.

Topology

[!NOTE] This sample is configured to allow sign-ins with personal Microsoft accounts ONLY using the /consumers endpoint. If you would like to allow sign-ins with work and school accounts in your tenant, see this note. Learn more about supported account types and validation differences between them.

Contents

File/folder Description
AppCreationScripts Contains Powershell scripts to automate app registration.
ReadmeFiles Sample readme files.
ProfileAPI Source code of the ProfileAPI.
ProfileSPA Source code of the ProfileSPA.
CHANGELOG.md List of changes to the sample.
CONTRIBUTING.md Guidelines for contributing to the sample.
README.md This README file.
LICENSE The license for the sample.

Setup

Prerequisites

  • Node.js must be installed to run this sample.
  • Dotnet Core SDK must be installed to run this sample.
  • An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant.
  • A personal Microsoft account is needed. This sample will not work with work or school accounts.
  • We recommend the VS Code for running and debugging this cross-platform application.
  • We recommend the Redux DevTools browser extension for monitoring your Redux store.

Steps

Using a command line interface such as VS Code integrated terminal, follow the steps below:

Step 1. Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/ms-identity-javascript-react-spa-dotnetcore-webapi-obo.git

or download and extract the repository .zip file.

[!NOTE] Given that the name of the sample is quiet long, and so are the names of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid the 256 character path length limitation on Windows.

Step 2. Install .NET Core API dependencies

cd ProfileAPI
dotnet restore

Step 3. Trust development certificates

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

Learn more about HTTPS in .NET Core.

Step 4. Install Angular SPA dependencies

cd ProfileSPA
npm install

Step 4: Register the sample application with your Azure Active Directory tenant

There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:

Expand this section if you want to use this automation:
  1. On Windows, run PowerShell and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

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

Register the service: ProfileAPI

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Select New registration.
  3. When the Register an application page 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 ProfileAPI.
    • Change Supported account types to Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
    • Select Register to create the application.
  4. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the configuration file for this projects.
  5. From the Certificates & secrets page, in the Client secrets section, choose New client secret:
    • Type a key description (of instance app secret),
    • Select a key duration of either In 1 year, In 2 years, or Never Expires.
    • When you press the Add button, the key value will be displayed, copy, and save the value in a safe location.
    • You'll need this key later to configure the project. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.
  6. Select the API permissions section
    • Click the Add a permission button and then,
    • Ensure that the Microsoft APIs tab is selected
    • In the Commonly used Microsoft APIs section, click on Microsoft Graph
    • In the Delegated permissions section, ensure that the right permissions are checked: User.Read and offline_access. Use the search box if necessary.
    • Select the Add permissions button.
  7. Select the Expose an API section, and:
    • Click Set next to the Application ID URI to generate a URI that is unique for this app (in the form of api://{clientId}).
    • Select Add a scope
    • Enter the following parameters
      • for Scope name use access_as_user
      • Keep Admins and users for Who can consent
      • in Admin consent display name type Access ProfileAPI as a user
      • in Admin consent description type Accesses the ProfileAPI Web API as a user
      • in User consent display name type Access ProfileAPI as a user
      • in User consent description type Accesses the ProfileAPI Web API as a user
      • Keep State as Enabled
      • Select Add scope

Register the client: ProfileSPA

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Select New registration.
  3. When the Register an application page 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 ProfileSPA.
    • Change Supported account types to Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
    • Select Register to create the application.
  4. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the configuration file for this projects.
  5. From the app's Overview page, select the Authentication section.
    • Click Add a platform button.
    • Select Single-page Applications on the right blade.
    • Add a Redirect URIs, for instance http://localhost:3000.
    • Click Configure.
  6. Select the API permissions section
    • Click the Add a permission button and then,
    • Ensure that the My APIs tab is selected
    • In the list of APIs, select the ProfileAPI API, or the name you entered for the Web API
    • In the Delegated permissions section, ensure that the right permissions are checked: access_as_user. Use the search box if necessary.
    • Select the Add permissions button.
  7. Now you need to leave the registration for ProfileSPA and go back to your app registration for ProfileAPI.
    • From the app's Overview page, select the Manifest section.
    • Find the entry for KnownClientApplications, and add the Application (client) ID of the ProfileSPA application copied from the Azure portal. i.e. KnownClientApplications: [ "your-client-id-for-ProfileSPA" ]
Configure the service app (ProfileAPI) to use your app registration

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the ProfileAPI\appsettings.json file
  2. Find the app key Domain and replace the existing value with your Azure AD tenant name.
  3. Find the app key ClientId and replace the existing value with the application ID (clientId) of the ProfileAPI application copied from the Azure portal.
  4. Find the app key ClientSecret and replace the existing value with the Client Secret of the ProfileAPI application copied from the Azure portal.
Configure the client app (ProfileSPA) to use your app registration

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the ProfileSPA\src\utils\authConfig.js file
  2. Find the app key clientId and replace the existing value with the application ID (clientId) of the ProfileSPA application copied from the Azure portal.
  3. Find the app key redirectUri and replace the existing value with the base address of the ProfileSPA project (by default http://localhost:3000/).
  4. Find the app key resourceUri and replace the existing value with the base address of the ProfileAPI project (by default https://localhost:44351/api/profile).
  5. Find the app key resourceScope and replace the existing value with Scope you created earlier api://{client_id}/.default.

Run the sample

Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:

cd ../
cd ProfileAPI
dotnet run

In a separate console window, execute the following commands

cd ProfileSPA
npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Sign-in using the button on top-right corner.
  3. If this is your first time sign-in, you will be redirected to the onboarding page (the app will try to make a GET request: if this is the first time, it will fail -this is expected).
  4. Hit "Accept" and a new account will be created for you in the database, pre-populated by the information about you fetched from the MS Graph API.
  5. Submit your changes. When you sign-in next time, the application will recognize you and show you the profile associated with your Id in the database.

[!NOTE] Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.

Debugging the sample

To debug the .NET Core Web API that comes with this sample, install the C# extension for Visual Studio Code.

Learn more about using .NET Core with Visual Studio Code.

Key concepts

This sample demonstrates the following Azure AD and Microsoft Identity Platform workflows:

  • How to protect a Web API.
  • How to configure application parameters.
  • How to sign-in & sign-out.
  • How to acquire an access token.
  • How to recognize a user from an id token's "oid" claim.
  • How to make a Web API call with the access token.
  • How to authorize Web API a to act on a user's behalf.

More information

For more information, visit the following links:

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 [msal dotnet angular azure-active-directory].

If you find a bug in the sample, please raise the issue on GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

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.

About

A React & Redux single-page application that authorizes an ASP.NET Core web API to call MS Graph API on its behalf

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 38.8%
  • PowerShell 38.3%
  • C# 19.3%
  • HTML 2.8%
  • CSS 0.8%