将身份验证令牌添加到AJAX调用,以获取使用Azure Active Directory身份验证保护的Web API

bla*_*cer -2 javascript active-directory azure-active-directory adal adal.js

我有一个基于JavaScript的基于JavaScript的网页.我需要在https://XYZ.azurewebsites.net上调用我的Web API,该API 使用Azure Active Directory身份验证进行保护.

为此,我已将ADAL.js添加到我的网站,在AAD中将我的网站/ webapp注册为Native Client.我不确定无声地获取身份验证令牌的最少量代码.

在vanilla JavaScript中获取身份验证令牌需要做的最小步骤是什么?

注意:我在GitHub上的Azure AD身份验证中经历了大量示例.但是他们都建议克隆repo并替换Audience,Tenants等的值.我需要的只是一个简单的vanilla JS函数来做同样的事情而没有这些样本中的所有膨胀代码.

Phi*_*ret 5

一种使用ADAL.JS(和vanilla JavaScript)的直接方法:

  1. 配置实例AuthenticationContext.
  2. 使用AuthenticationContext.login()登录.
  3. 使用AuthenticationContext.handleWindowCallback()处理令牌请求的响应.
  4. 使用AuthenticationContext.acquireToken()来获得访问令牌.
  5. 使用收到的访问令牌发出API请求.

这是一个完整的最小示例,它获取Microsoft Graph API的访问令牌(受Azure AD保护的API的示例),并使用它来进行AJAX调用以检索已登录用户的配置文件.注释中的数字对应于上述步骤.

(我还发布了一个Gist,它有一个稍微完整的版本,你可以试试.)

<html>
    <head>
        <title>Minimal sample using ADAL.JS</title>
        <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.11/js/adal.min.js"></script>
    </head>
    <body>
        <p>
            <!-- #2: Use ADAL's login() to sign in -->
            <a href="#" onclick="authContext.login(); return false;">Log in</a> |
            <a href="#" onclick="authContext.logOut(); return false;">Log out</a>
        </p>

        <script type="text/javascript">

            // #1: Set up ADAL
            var authContext = new AuthenticationContext({
                clientId: 'c24f035c-1ff6-4dfa-b76d-c75a29ad2c3c',
                postLogoutRedirectUri: window.location
            });

            // #3: Handle redirect after token requests
            if (authContext.isCallback(window.location.hash)) {

                authContext.handleWindowCallback();
                var err = authContext.getLoginError();
                if (err) {
                    // TODO: Handle errors signing in and getting tokens
                }

            } else {

                // If logged in, get access token and make an API request
                var user = authContext.getCachedUser();
                if (user) {

                    console.log('Signed in as: ' + user.userName);

                    // #4: Get an access token to the Microsoft Graph API
                    authContext.acquireToken(
                        'https://graph.microsoft.com',
                        function (error, token) {

                            // TODO: Handle error obtaining access token
                            if (error || !token) { return; }

                            // #5: Use the access token to make an AJAX call
                            var xhr = new XMLHttpRequest();
                            xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
                            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState === 4 && xhr.status === 200) {
                                    // TODO: Do something with the response
                                    console.log(xhr.responseText);
                                } else {
                                    // TODO: Do something with the error 
                                    // (or other non-200 responses)
                                }
                            };
                            xhr.send();
                        }
                    );
                } else {

                    console.log('Not signed in.')
                }
            }
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)