Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Nov 16, 2023. It is now read-only.

An Angular single-page application that authenticates users with Azure AD and calls a protected ASP.NET Core web API using MSAL Angular

NotificationsYou must be signed in to change notification settings

Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi

 
 

Repository files navigation

page_typelanguagesproductsdescriptionurlFragment
sample
javascript
typescript
csharp
angular
dotnet-core
msal-angular
microsoft-identity-web
azure-active-directory
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
  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. Deployment
  11. More information
  12. Community Help and Support
  13. Contributing

Overview

This sample demonstrates a cross-platform application suite involving an Angular SPA (TodoListSPA) calling an ASP.NET Core web API (TodoListAPI) secured withAzure Active Directory (Azure AD) using theMicrosoft Authentication Library for Angular (Preview) (MSAL Angular).

Scenario

  • TodoListSPA useMSAL-Angular to sign-in a user.
  • The app then obtains anaccess token fromAzure AD for the signed-in user.
  • Theaccess token is then used to authorize the call to theTodoListAPI.
  • TodoListAPI usesMSAL.NET andMicrosoft.Identity.Web to protect its endpoint and accept authorized calls.

Topology

Contents

File/folderDescription
AppCreationScriptsContains Powershell scripts to automate app registrations.
ReadmeFilesSample readme files.
TodoListAPISource code of the TodoList API.
TodoListSPASource code of the TodoList client SPA.
CHANGELOG.mdList of changes to the sample.
CONTRIBUTING.mdGuidelines for contributing to the sample.
README.mdThis README file.
LICENSEThe license for the sample.

Prerequisites

Setup

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

Step 1. Clone or download this repository

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.

Step 2. Install .NET Core API dependencies

    cd TodoListAPI    dotnet restore

Step 3. Trust development certificates

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

Learn more aboutHTTPS in .NET Core.

Step 4. Install Angular SPA dependencies

    cd ../    cd TodoListSPA    npm install

Registration

Register the sample applications 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:

  • 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:
  1. On Windows, run PowerShell and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy-ExecutionPolicy RemoteSigned-ScopeProcess-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 inApp Creation ScriptsThe scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

  5. Follow the section on "Running the sample" below.

Register the service app (TodoListAPI)

Note

This sample isnot configured to be a multi-tenant sample (learn more abouttenancy in Azure AD). If you would like to authorize users from other tenants to use this application, you may want to reviewthis tutorial first.

  1. Navigate to the Microsoft identity platform for developersApp registrations page.
  2. SelectNew registration.
  3. In theRegister an application page that appears, enter your application's registration information:
    • In theName section, enter a meaningful application name that will be displayed to users of the app, for exampleTodoListAPI.
    • UnderSupported account types, selectAccounts in this organizational directory only.
  4. SelectRegister to create the application.
  5. In the app's registration screen, find and note theApplication (client) ID. You use this value in your app's configuration file(s) later in your code.
  6. SelectSave to save your changes.
  7. In the app's registration screen, click on theExpose 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 obtainaccess tokens for.The first thing that we need to do is to declare the uniqueresource URI that the clients will be using to obtain access tokens for this API. To declare an resource URI, follow the following steps:
    • ClickSet next to theApplication ID URI to generate a URI that is unique for this app.
    • For this sample, accept the proposed Application ID URI (api://{clientId}) by selectingSave.
  8. All APIs have to publish a minimum of onescope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
    • SelectAdd a scope button open theAdd a scope screen and Enter the values as indicated below:
      • ForScope name, useaccess_as_user.
      • SelectAdmins and users options forWho can consent?
      • ForAdmin consent display name typeAccess TodoListAPI
      • ForAdmin consent description typeAllows the app to access TodoListAPI as the signed-in user.
      • ForUser consent display name typeAccess TodoListAPI
      • ForUser consent description typeAllow the application to access TodoListAPI on your behalf.
      • KeepState asEnabled
      • Click on theAdd scope button on the bottom to save this scope.

Configure the service app (TodoListAPI) to use your app registration

Open the project in your IDE to configure the code.

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

  1. Open theTodoListAPI\appsettings.json file.
  2. Find the keyDomain and replace the existing value with your Azure AD tenant name.
  3. Find the keyClientId and replace the existing value with the application ID (clientId) ofTodoListAPI app copied from the Azure Portal.
  4. Find the keyTenantId and replace the existing value with your Azure AD tenant ID.

Register the client app (TodoListSPA)

  1. Navigate to the Microsoft identity platform for developersApp registrations page.
  2. SelectNew registration.
  3. In theRegister an application page that appears, enter your application's registration information:
    • In theName section, enter a meaningful application name that will be displayed to users of the app, for exampleTodoListSPA.
    • UnderSupported account types, selectAccounts in this organizational directory only.
    • In theRedirect URI (optional) section, selectSingle-page application in the combo-box and enter the following redirect URI:http://localhost:4200/.
  4. SelectRegister to create the application.
  5. In the app's registration screen, find and note theApplication (client) ID. You use this value in your app's configuration file(s) later in your code.
  6. In the app's registration screen, click on theAPI permissions blade in the left to open the page where we add access to the APIs that your application needs.
    • Click theAdd a permission button and then,
    • Ensure that theMy APIs tab is selected.
    • In the list of APIs, select the APITodoListAPI.
    • In theDelegated permissions section, select theaccess_as_user in the list. Use the search box if necessary.
    • Click on theAdd permissions button at the bottom.

Configure the client app (TodoListSPA) to use your app registration

Open the project in your IDE to configure the code.

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

  1. Open theTodoListSPA\src\app\auth-config.json file.
  2. Find the keyclientId and replace the existing value with the application ID (clientId) ofTodoListSPA app copied from the Azure Portal.
  3. Find the keytenantId and replace the existing value with your Azure AD tenant ID.
  4. Find the keyredirectUri and replace the existing value with the Redirect URI forTodoListSPA. (by defaulthttp://localhost:4200/).
  5. Find the keypostLogoutRedirectUri and replace the existing value with the base address ofTodoListSPA (by defaulthttp://localhost:4200/.
  6. Find the keyresourceUri and replace the existing value with the base address ofTodoListAPI (by defaulthttps://localhost:44351/api/todolist/).
  7. Find the app keyresourceScopes and replace the existing value withscope you created earlierapi://{clientId}/access_as_user.

Run the sample

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

Explore the sample

  1. Open your browser and navigate tohttp://localhost:4200.
  2. Sign-in using the button on top-right corner.
  3. Click on theGet my tasks button to access your todo list.

Screenshot

ℹ️ Consider taking a moment toshare your experience with us. If the sample did not work for you as expected, then please reach out to us using theGitHub Issues page.

Debugging the sample

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

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

About the code

Initialization

Initialize MSAL Angular client by passing the configuration parameters inauth-config.json to the MSALInstanceFactory inapp.module.ts. This application is configured to be a single-tenant app on Azure AD:

exportfunctionMSALInstanceFactory():IPublicClientApplication{returnnewPublicClientApplication({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 asMsalService:

@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent{constructor(privateauthService:MsalService){}}login(){this.authService.loginRedirect();}

Calling a web API

Set up anMSALInterceptor to keep track of the protected resources that you need access to. This will intercept HTTP calls and automatically retrieve necessary tokens, as defined inprotectedResourceMap.

exportfunctionMSALInterceptorConfigFactory():MsalInterceptorConfiguration{constprotectedResourceMap=newMap<string,Array<string>>();protectedResourceMap.set(auth.resources.todoListApi.resourceUri,auth.resources.todoListApi.resourceScopes);return{interactionType:InteractionType.Redirect,    protectedResourceMap};}

CORS configuration

You need to setCORS policy to be able to call theTodoListAPI inStartup.cs. For the purpose of this sample, we are setting it to allowany 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();}));

Deployment

Deploying web API to Azure App Services

There is one web API in this sample. To deploy it toAzure App Services, you'll need to:

  • create anAzure App Service
  • publish the projects to theApp Services

Publish your files (TodoListAPI)

  1. Sign-in toApp Service using an Azure AD Account.

  2. Open theTodoListAPI project folder.

  3. ChooseView >Terminal from the main menu.

  4. The terminal opens in theTodoListAPI folder.

  5. Run the following command:

    dotnet publish --configuration Release
  6. Publish folder is created under pathbin/Release/<Enter_Framework_FolderName>.

  7. Right-click onPublish folder and selectDeploy to Web App.

  8. SelectCreate New Web App, enter a unique name for the app.

  9. SelectWindows as the OS. PressEnter.

Disable Azure App Services default authentication (TodoListAPI)

  1. Go toAzure Portal, and locate your project there.
    • On the Settings tab, selectAuthentication/Authorization. Make sureApp Service Authentication is Off. SelectSave.
  2. Browse your website. If you see the default web page of the project, the publication was successful.

Enable cross-origin resource sharing (CORS) (TodoListAPI)

  1. Go toAzure Portal, and locate your project there.
    • On the API tab, selectCORS. Check the boxEnable Access-Control-Allow-Credentials.
    • UnderAllowed origins, add the coordinates of your published website.

Deploying SPA to Azure Storage

There is one single-page application in this sample. To deploy it toAzure 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 useVS Code Azure Tools extension for deployment,watch the tutorial offered by Microsoft Docs.

Build and upload theTodoListSPA to an Azure Storage blob

Build your project to get a distributable files folder, where your builthtml,css andjavascript 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 andnot the entire folder itself.

ℹ️ If you don't have an account already, see:How to create a storage account.

  1. Sign in to theAzure portal.
  2. Locate your storage account and display the account overview.
  3. SelectStatic website to display the configuration page for static websites.
  4. SelectEnabled to enable static website hosting for the storage account.
  5. In theIndex document name field, specify a default index page (For example:index.html).
  6. The defaultindex page is displayed when a user navigates to the root of your static website.
  7. SelectSave. The Azure Portal now displays your static website endpoint. Make a note of thePrimary endpoint field.
  8. In theTodoListSPA project source code, update your configuration file with thePrimary endpoint field as your newRedirect URI (you will register this URI later).
  9. Next, selectStorage Explorer.
  10. Expand theBLOB CONTAINERS node, and then select the$web container.
  11. Choose theUpload button to upload files.
  12. If you intend for the browser to display the contents of file, make sure that the content type of that file is set totext/html.
  13. In the pane that appears beside theaccount overview page of your storage account, selectStatic Website. The URL of your site appears in thePrimary endpoint field. In the next section, you will register this URI.
Update the Azure AD app registration for TodoListSPA
  1. Navigate back to to theAzure portal.
  2. In the left-hand navigation pane, select theAzure Active Directory service, and then selectApp registrations.
  3. In the resulting screen, selectTodoListSPA.
  4. In the app's registration screen, selectAuthentication in the menu.
    • In theRedirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
      • https://TodoListSPA.azurewebsites.net/

Update authentication configuration parameters (TodoListSPA)

  1. In your IDE, locate theTodoListSPA project. Then, openTodoListSPA\src\app\auth-config.json.
  2. Find the key forredirect URI and replace its value with the address of the web app you published, for example,https://TodoListSPA.azurewebsites.net.
  3. Find the key forweb API endpoint and replace its value with the address of the web API you published, for example,https://TodoListAPI.azurewebsites.net/api.

More information

For more information, visit the following links:

Community Help and Support

UseStack 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 [msaldotnetangularazure-active-directory].

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

To provide a recommendation, visit the followingUser Voice page.

Contributing

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

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

This project has adopted theMicrosoft Open Source Code of Conduct.For more information see theCode of Conduct FAQ orcontactopencode@microsoft.com with any additional questions or comments.

About

An Angular single-page application that authenticates users with Azure AD and calls a protected ASP.NET Core web API using MSAL Angular

Topics

Resources

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors9


[8]ページ先頭

©2009-2025 Movatter.jp