使用activedirectory身份验证在JavaScript中调用Azure API应用程序

Make API call to Azure API App in JavaScript with Active Directory authentication

本文关键字:调用 Azure API 应用程序 JavaScript activedirectory 身份验证 使用      更新时间:2023-09-26

我实现了一个Java API后端,它作为API应用程序托管在Azure中。我启用了Active Directory身份验证。在api应用程序的CORS设置中,我配置了允许来自每个源的调用,只是将星号设置为URL。

现在我想从本地AngularJS应用程序访问API。我的angular代码如下所示:

angular.module('demo', [])
    .controller('GetDataController', function($scope, $http) {
        $scope.login = function(user){
            console.log("user: " + user, user);
            $http.defaults.useXDomain = true;
            delete $http.defaults.headers.common['X-Requested-With'];
            $http.get('http://<myapiapp>.azurewebsites.net/api/contacts').
            then(function(response) {
                $scope.greeting = response.data;
                console.log("$scope.greeting: " + $scope.greeting, $scope.greeting);
            });
        }
    });

但是我仍然在控制台收到以下错误:

XMLHttpRequest cannot load https://login.windows.net/
12141bed-36f0-4fc6-b70c-43483f616eb7/oauth2/autho…
%2Fapi%2Fcontacts%23&nonce=ea6b31321cda45d6a4e881fbd0062974_20161026094547.
Redirect from 'https://login.windows.net/12141bed-36f0-4fc6-b70c-43483f616eb7/
oauth2/autho…%2Fapi%2Fcontacts%23&
nonce=ea6b31321cda45d6a4e881fbd0062974_20161026094547' to 
'https://login.microsoftonline.com/12141bed-36f0-4fc6-b70c-43483f616eb7/
oaut…%2Fapi%2Fcontacts%23&nonce=ea6b31321cda45d6a4e881fbd0062974_20161026094547' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource. 
Origin 'null' is therefore not allowed access.

那么如何从AngularJS代码中获得访问权限?

这也与我在这里的帖子有关,我试图通过curl调用来访问

似乎你正在直接生成HTTP请求,你的Web应用程序受Azure AD保护。对于这种情况,你可以尝试在你的angularJs客户端中为js实现ADAL。利用adal来获得认证令牌,当你在Angular中调用你的Web应用时,它会在HTTP请求中添加认证头。

如有任何问题,请随时与我联系。