AngularJS + ADAL.JS set Resource ID (Audience)

主宰稳场 提交于 2019-12-07 10:52:38

问题


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/'.

回答1:


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
            );
}]);


来源:https://stackoverflow.com/questions/31288193/angularjs-adal-js-set-resource-id-audience

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!