ranthonissen
ranthonissen

Reputation: 1503

Cannot get an Angular SPA to authenticate an ASP.NET MVC WebAPI with Azure Active Directory

I have created a single page application in Angular 2 and an ASP.NET MVC WebAPI that both require Azure Active Directory authentication. Both applications are registered in the Azure Portal, and have OAuth2 enabled. The SPA also has permission to access the WebAPI

In the SPA, I use adaljs, which works as expected. The ASP.NET Web API is configured to use Windows Azure Active Directory Bearer Authentication, which also works as far as I can tell.

When the SPA requests data from the WebAPI it sends a bearer authorization token in the header, but the requests gets denied (status 401 UNAUTHORIZED).

I have created a sample project in in github: https://github.com/ranthonissen/angular2-adaljs-webapi, and described the steps I followed in more detail here: https://dotronald.be/creating-an-angular-single-page-application-with-azure-active-directory-and-adal-js-that-uses-an-asp-net-webapi/

What am I missing to get this setup to work?

Upvotes: 1

Views: 798

Answers (1)

Fei Xue
Fei Xue

Reputation: 14649

Based on the code, you were acquiring the access token using the clientId instead of app id URI of the second app.

To fix this issue, we can add resource id parameter in the SPA like below:

secret.service.ts

import { Injectable } from '@angular/core';
@Injectable()
export class SecretService {
    public get adalConfig(): any {
        return {
            tenant: 'adnewfei.onmicrosoft.com',
            clientId: 'aac92cf9-32ab-4004-aeab-1046389dff79',
            redirectUri: window.location.origin + '/',
            postLogoutRedirectUri: window.location.origin + '/',
            resourceId:"https://ADNewFei.onmicrosoft.com/webAPIFei"
        };
    }
}

The value of resourceId is the App ID URI of the app you register for the web API. And it should match the value you config in the web.config of web API project like below:

enter image description here

  <appSettings>
    <add key="ida:ClientId" value="29fc9b4c-4d77-4ffa-b4af-674d6b0584f7" />
    <add key="ida:Tenant" value="adnewfei.onmicrosoft.com" />
    <add key="ida:Audience" value="https://ADNewFei.onmicrosoft.com/webAPIFei" />
    <add key="ida:Password" value="xxxxxx" />
  </appSettings>

Upvotes: 3

Related Questions