page_type | languages | products | description | urlFragment | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
|
|
This sample demonstrates an Angular single-page application calling a .NET Core web API secured with Azure Active Directory using MSAL Angular v2 |
ms-identity-javascript-angular-spa-aspnetcore-webapi |
An Angular single-page application that authenticates users against Azure AD and calls a protected ASP.NET Core web API
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- Deployment
- More information
- Community Help and Support
- Contributing
This sample demonstrates a cross-platform application suite involving an Angular SPA (TodoListSPA) calling an ASP.NET Core web API (TodoListAPI) secured with Azure Active Directory (Azure AD) using the Microsoft Authentication Library for Angular (Preview) (MSAL Angular).
- TodoListSPA use MSAL-Angular to sign-in a user.
- The app then obtains an access token from Azure AD for the signed-in user.
- The access token is then used to authorize the call to the TodoListAPI.
- TodoListAPI uses MSAL.NET and Microsoft.Identity.Web to protect its endpoint and accept authorized calls.
File/folder | Description |
---|---|
AppCreationScripts |
Contains Powershell scripts to automate app registrations. |
ReadmeFiles |
Sample readme files. |
TodoListAPI |
Source code of the TodoList API. |
TodoListSPA |
Source code of the TodoList client SPA. |
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. |
- Node.js must be installed to run this sample.
- Dotnet Core SDK must be installed to run this sample.
- VS Code for running and debugging this cross-platform application.
- VS Code Azure Tools Extension extension is recommended for interacting with Azure through VS Code interface.
- 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.
Using a command line interface such as VS Code integrated terminal, follow the steps below:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi.git
⚠️ Given that the name of the sample is quite 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 file size limitations on Windows.
cd TodoListAPI
dotnet restore
dotnet dev-certs https --clean
dotnet dev-certs https --trust
Learn more about HTTPS in .NET Core.
cd ../
cd TodoListSPA
npm install
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- either follow the steps below for manual registration,
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the configuration files.
Expand this section if you want to use this automation:
-
On Windows, run PowerShell 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.
-
Follow the section on "Running the sample" below.
Note
This sample is not configured to be a multi-tenant sample (learn more about tenancy in Azure AD). If you would like to authorize users from other tenants to use this application, you may want to review this tutorial first.
- Navigate to the Microsoft identity platform for developers App registrations page.
- 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
TodoListAPI
. - Under Supported account types, select Accounts in this organizational directory only.
- 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.
- Select Save to save your changes.
- In the app's registration screen, click on the Expose an API blade to the left to open the page where you can declare the parameters to expose this app as an API for which client applications can obtain access tokens for.
The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this API. To declare an resource URI, follow the following steps:
- Click
Set
next to the Application ID URI to generate a URI that is unique for this app. - For this sample, accept the proposed Application ID URI (api://{clientId}) by selecting Save.
- Click
- All APIs have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_as_user
. - Select Admins and users options for Who can consent?
- For Admin consent display name type
Access TodoListAPI
- For Admin consent description type
Allows the app to access TodoListAPI as the signed-in user.
- For User consent display name type
Access TodoListAPI
- For User consent description type
Allow the application to access TodoListAPI on your behalf.
- Keep State as Enabled
- Click on the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
Open the project in your IDE to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
TodoListAPI\appsettings.json
file. - Find the key
Domain
and replace the existing value with your Azure AD tenant name. - Find the key
ClientId
and replace the existing value with the application ID (clientId) ofTodoListAPI
app copied from the Azure Portal. - Find the key
TenantId
and replace the existing value with your Azure AD tenant ID.
- Navigate to the Microsoft identity platform for developers App registrations page.
- 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
TodoListSPA
. - Under Supported account types, select Accounts in this organizational directory only.
- In the Redirect URI (optional) section, select Single-page application in the combo-box and enter the following redirect URI:
http://localhost:4200/
.
- 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, click on the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Click the Add a permission button and then,
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
TodoListAPI
. - In the Delegated permissions section, select the access_as_user in the list. Use the search box if necessary.
- Click on the Add permissions button at the bottom.
Open the project in your IDE to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
TodoListSPA\src\app\auth-config.json
file. - Find the key
clientId
and replace the existing value with the application ID (clientId) ofTodoListSPA
app copied from the Azure Portal. - Find the key
tenantId
and replace the existing value with your Azure AD tenant ID. - Find the key
redirectUri
and replace the existing value with the Redirect URI forTodoListSPA
. (by defaulthttp://localhost:4200/
). - Find the key
postLogoutRedirectUri
and replace the existing value with the base address ofTodoListSPA
(by defaulthttp://localhost:4200/
. - Find the key
resourceUri
and replace the existing value with the base address ofTodoListAPI
(by defaulthttps://localhost:44351/api/todolist/
). - Find the app key
resourceScopes
and replace the existing value with scope you created earlierapi://{clientId}/access_as_user
.
Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:
cd ../
cd TodoListSPA
npm start
In a separate console window, execute the following commands
cd TodoListAPI
dotnet run
- Open your browser and navigate to
http://localhost:4200
. - Sign-in using the button on top-right corner.
- Click on the Get my tasks button to access your todo list.
ℹ️ Consider taking a moment to share your experience with us. If the sample did not work for you as expected, then please reach out to us using the GitHub Issues page.
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.
Initialize MSAL Angular client by passing the configuration parameters in auth-config.json to the MSALInstanceFactory in app.module.ts. This application is configured to be a single-tenant app on Azure AD:
export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication({
auth: {
clientId: auth.credentials.clientId,
authority: 'https://login.microsoftonline.com/' + auth.credentials.tenantId,
redirectUri: auth.configuration.redirectUri
},
cache: {
cacheLocation: BrowserCacheLocation.LocalStorage,
storeAuthStateInCookie: isIE, // set to true for IE 11
},
});
}
Then, in your components, MSAL Angular client will be available as MsalService
:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private authService: MsalService) {}
}
login() {
this.authService.loginRedirect();
}
Set up an MSALInterceptor to keep track of the protected resources that you need access to. This will intercept HTTP calls and automatically retrieve necessary tokens, as defined in protectedResourceMap
.
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap.set(auth.resources.todoListApi.resourceUri, auth.resources.todoListApi.resourceScopes);
return {
interactionType: InteractionType.Redirect,
protectedResourceMap
};
}
You need to set CORS policy to be able to call the TodoListAPI in Startup.cs. For the purpose of this sample, we are setting it to allow any domain and methods. In production, you should modify this to allow only the domains and methods you designate.
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
There is one web API in this sample. To deploy it to Azure App Services, you'll need to:
- create an Azure App Service
- publish the projects to the App Services
-
Sign-in to App Service using an Azure AD Account.
-
Open the
TodoListAPI
project folder. -
Choose View > Terminal from the main menu.
-
The terminal opens in the
TodoListAPI
folder. -
Run the following command:
dotnet publish --configuration Release
-
Publish folder is created under path
bin/Release/<Enter_Framework_FolderName>
. -
Right-click on Publish folder and select Deploy to Web App.
-
Select Create New Web App, enter a unique name for the app.
-
Select Windows as the OS. Press Enter.
- Go to Azure Portal, and locate your project there.
- On the Settings tab, select Authentication/Authorization. Make sure
App Service Authentication
is Off. Select Save.
- On the Settings tab, select Authentication/Authorization. Make sure
- Browse your website. If you see the default web page of the project, the publication was successful.
- Go to Azure Portal, and locate your project there.
- On the API tab, select CORS. Check the box Enable Access-Control-Allow-Credentials.
- Under Allowed origins, add the coordinates of your published website.
There is one single-page application in this sample. To deploy it to Azure Storage, you'll need to:
- create an Azure Storage blob and obtain website coordinates
- build your project and upload it to Azure Storage blob
- update config files with website coordinates
ℹ️ If you would like to use VS Code Azure Tools extension for deployment, watch the tutorial offered by Microsoft Docs.
Build your project to get a distributable files folder, where your built html
, css
and javascript
files will be generated.
cd TodoListSPA
npm run build
Then follow the steps below:
⚠️ When uploading, make sure you upload the contents of your distributable files folder and not the entire folder itself.
ℹ️ If you don't have an account already, see: How to create a storage account.
- Sign in to the Azure portal.
- Locate your storage account and display the account overview.
- Select Static website to display the configuration page for static websites.
- Select Enabled to enable static website hosting for the storage account.
- In the Index document name field, specify a default index page (For example:
index.html
). - The default index page is displayed when a user navigates to the root of your static website.
- Select Save. The Azure Portal now displays your static website endpoint. Make a note of the Primary endpoint field.
- In the
TodoListSPA
project source code, update your configuration file with the Primary endpoint field as your new Redirect URI (you will register this URI later). - Next, select Storage Explorer.
- Expand the BLOB CONTAINERS node, and then select the
$web
container. - Choose the Upload button to upload files.
- If you intend for the browser to display the contents of file, make sure that the content type of that file is set to
text/html
. - In the pane that appears beside the account overview page of your storage account, select Static Website. The URL of your site appears in the Primary endpoint field. In the next section, you will register this URI.
- Navigate back to to the Azure portal.
- In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations.
- In the resulting screen, select
TodoListSPA
. - In the app's registration screen, select Authentication in the menu.
- In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
https://TodoListSPA.azurewebsites.net/
- In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
- In your IDE, locate the
TodoListSPA
project. Then, openTodoListSPA\src\app\auth-config.json
. - Find the key for redirect URI and replace its value with the address of the web app you published, for example, https://TodoListSPA.azurewebsites.net.
- Find the key for web API endpoint and replace its value with the address of the web API you published, for example, https://TodoListAPI.azurewebsites.net/api.
For more information, visit the following links:
-
Articles about the Microsoft identity platform are at http://aka.ms/aaddevv2, with a focus on:
-
To lean more about the application registration, visit:
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.
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.