Access tokens for several web api from one Angular application


Scenario
          
          I have an angular app authenticated with azure AD, the same need to communicate with n no of azure ad authenticated Web Api. I don't want to maintain different client id, secret and tokens. 

Solution
       We are going to achieve this with scopes in app registration. Used technologies .net core 3.1 API, Angular 9 UI, MSAL for authentication.

Step 1: Register 2 apps with single tenant - default directory only
           1. Web Api 
           2. Angular UI
Step 2: In web Api add scope from the left menu expose an API 
           1. set application ID URI
           2. Add a scope - use consent admin and user.
Step 3: In angular app add a platform from left menu Authentication 
           1. Select single page application and enter redirect URI, configure
           2. scroll below and check Access tokens and ID Tokens

Configure Web API for Auth
appsettings.json


startup.cs

Controller- Add [Authorize] attribute

Configure Angular for Auth
Create 2 Component and call those in app.component.html in   <router-outlet ></router-outlet>
Create component / page : ng generate component profile
Create component / page : ng generate component home
Protect the  profile page with  canActivate:[MsalGuard]

Create Service : ng generate service data and use the acces token stored in local storage for api auth


app.module.ts
In this I have added the scope of web api in consentScope and ProtectedResourceMap

app.component.ts

profile.component.ts

Test
Execute the web api in local
Execute the angular app with ng serve 
Navigate to the profile page a popup will appear for login once login it seeks for the permission to the scope for web app and accept it.
Now we can access the web api with same access token.

Download the source here : https://github.com/veekee1988/AzureAD

Comments

  1. Hi Vivek, do you have an example that addresses the problem statement specified? i.e. Single SPA that must access multiple protected APIs? This post shows configuration for a single API

    ReplyDelete

Post a Comment

Popular posts from this blog

Azure Front Door - Path based routing rule

A simple introduction to SQL+ Dot Net