【问题标题】:Add authentication token to AJAX call for a Web API secured using Azure Active Directory authentication将身份验证令牌添加到使用 Azure Active Directory 身份验证保护的 Web API 的 AJAX 调用
【发布时间】:2017-01-05 11:48:15
【问题描述】:

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

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

在原生 JavaScript 中获取身份验证令牌所需的最少步骤是什么?

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

【问题讨论】:

  • “静默获取身份验证令牌”是什么意思。您的意思是在不提示用户登录的情况下尝试获取令牌?
  • 您能否指定您尝试使用的样本?
  • 您好,不提示用户登录就不能获取token吗?

标签: javascript active-directory azure-active-directory adal adal.js


【解决方案1】:

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

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

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

(我还发布了a Gist 一个稍微完整的版本,你可以try out live。)

<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>

【讨论】:

  • 您好,不提示用户登录就无法获取token吗?
  • 您的意思是如果用户已经登录,并且您只想刷新会话以获取新令牌?
  • 您好,抱歉回复晚了,不,我不是指刷新令牌,我知道刷新是静默的。我的意思类似于azure.microsoft.com/en-us/resources/samples/… 使用 UserPasswordCredential(user, password),如何在 Javascript 中实现这一点,我在 ADAL.js 中看不到任何此类 API 查看stackoverflow.com/questions/43607308/… 的答案,了解可能的身份验证类型,我想要实现的是第二个选项和 Javascript。
  • 不推荐使用用户名/密码流,ADAL 不支持 JavaScript。如果您假设只需一个用户名和密码就足以让所有用户登录,那么有大量情况会中断,并且通常认为这是一种不太安全的方法。
猜你喜欢
  • 2017-07-20
  • 2018-10-10
  • 2017-09-05
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
相关资源
最近更新 更多