Stuart.Sklinar
Stuart.Sklinar

Reputation: 3761

Calling an Azure AD secured Web API from Angular

I'm trying to create a PoC application set, WebApi with a Angular (other or variant frontend), using Azure AD to authenticate my Federation users.

I've got the backend working fine, with authentication/MFA working as expected, and showing sign-in prompts.

enter image description here

enter image description here

I've got the Microsoft samples for Angular apps, but i'm struggling with implementation of said app, who do I use MSAL to get a token on the frontend, and have the backend accept said token and authenticate as that federated user?

This is my app.module.ts code from the sample, where

export const protectedResourceMap:[string, string[]][]=[ ['https://localhost:5001/',['api://--------------/access_as_user']] , ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];

const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;

@NgModule({
  declarations: [
    AppComponent, HomeComponent, ProductComponent, ErrorComponent, ProductDetailComponent, TodoListComponent, UserDataComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes,{useHash:true}) ,
    MsalModule.forRoot({
        clientID: '-----------',
        authority: "https://login.microsoftonline.com/common/",
        validateAuthority: true,
        redirectUri: "http://localhost:4200/",
        cacheLocation : "localStorage",
        storeAuthStateInCookie: isIE, // set to true for IE 11
        postLogoutRedirectUri: "http://localhost:4200/",
        navigateToLoginRequestUrl: true,
        popUp: !isIE,
        consentScopes: [ "user.read", "openid", "profile", "api://------------/access_as_user"],
        unprotectedResources: ["https://www.microsoft.com/en-us/"],
        protectedResourceMap: protectedResourceMap,
        logger: loggerCallback,
        correlationId: '1234',
        piiLoggingEnabled: true
      }
    ),
  ],
  providers: [ProductService, TodoListService, HttpServiceHelper,
     {provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true}
  ],
  bootstrap: [AppComponent]
})

Upvotes: 1

Views: 1648

Answers (1)

Skel
Skel

Reputation: 1667

I use @azure/msal-angular - frontend NPM Package & passport-azure-ad - backend NPM Package

And we get the token from the front end and validate that on the backend and get the email that is attached to that user and link it up with a user on our DB. But this only happens after the token has been validated on the backend by the Microsoft Graph.

So on our login page this is the code we import import { BroadcastService, MsalService } from '@azure/msal-angular';

In NgOnInit we have this

  ngOnInit() {
    this.broadcastService.subscribe('msal:loginFailure', payload => {
      this.loggedIn = false;
      this.loaded = false;
    });
    this.broadcastService.subscribe('msal:loginSuccess', payload => {
      console.log(payload);
      if (payload instanceof Object) {
        // Do something
      }
    });
  }

This is the code i have on the actual microsoft login button

microsoftLogin() {
    this.loaded = true;
    this.msal
      .loginPopup()
      .then(token => {
        this.microsoftAPILogin(token); // A call to send the token to our API
        this.loaded = false;
        this.loggedIn = true;
      })
      .catch(err => {
        this.loggedIn = false;
        this.loaded = false;
      });
  }

Upvotes: 3

Related Questions