4

How can I use adal.js in AngularJS to get a bearer token for the audience https://management.azure.com from my javascript code?

I have created a Client application in the AD and set its permissions to allow it to access the "Windows Azure Service Management API". My angularjs code is as follows:

adalService.init(
            {
                instance: "https://login.windows.net/",
                tenant: "<something>.onmicrosoft.com",
                clientId: "<some id>",
                cacheLocation: 'localStorage',
                redirectUri: 'http://localhost:63691/index.html#/configure',
                endpoints: {
                    /* 'target endpoint to be called': 'target endpoint's resource ID' */
                    'https://management.azure.com/subscriptions?api-version=2014-04-01': 'https://management.azure.com/'
                }
            },
            $httpProvider
        );

If I use the token received by this adalService in POSTMAN to call https://management.azure.com/subscriptions?api-version=2014-04-01, I get the following error:

The access token has been obtained from wrong audience or resource '<some id>'. 
It should exactly match (including forward slash) with one of the allowed audiences 'https://management.core.windows.net/','https://management.azure.com/'.
Anindit Karmakar
  • 825
  • 1
  • 8
  • 26

1 Answers1

9

Okay so I found the solution after going through the source code of ADAL.JS here. At line 137, it looks at config.loginResource to see if it has been set when passing the config object to the init() function.

Putting it out there for anyone getting stuck:

If you need your token to have the claim for “https://management.azure.com/” (or any other resource URI), you can set the audience when initializing the AuthenticationContext like so:

app.config(['$routeProvider', '$httpProvider', 'adalAuthenticationServiceProvider', function ($routeProvider, $httpProvider, adalService) {
    adalService.init(
                {
                    instance: "https://login.microsoftonline.com/",
                    tenant: "<something>.onmicrosoft.com",
                    clientId: "<client-id>",
                    cacheLocation: 'localStorage', //optional
                    redirectUri: '<redirect-uri>',
                    loginResource: 'https://management.azure.com/' //to set AUDIENCE
                },
                $httpProvider
            );
}]);
Anindit Karmakar
  • 825
  • 1
  • 8
  • 26
  • Can I ask you how did you did this? I want to know why did not you use the endpoint in your adalService.init? – Bruno Gomes Sep 03 '15 at 17:17
  • It got past the authentication with this, but now ran into endless loop or renewing the token. – Jaanus Nov 25 '15 at 10:33
  • @Jaanus I had gotten the same problem. If you wait long enough, you'll see it is not an infinite loop. It stops refreshing after a while. Sadly, I did not figure out why this happens. – Anindit Karmakar Jan 04 '16 at 11:03