Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS + ADAL.JS set Resource ID (Audience)

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/'.
like image 573
Anindit Karmakar Avatar asked Jan 08 '23 00:01

Anindit Karmakar


1 Answers

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
            );
}]);
like image 176
Anindit Karmakar Avatar answered Jan 15 '23 02:01

Anindit Karmakar