最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add authentication token to AJAX call for a Web API secured using Azure Active Directory authentication - Stack Ove

programmeradmin1浏览0评论

I have a vanilla JavaScript based web page. I need to call my web API at which is secured using Azure Active Directory authentication.

For doing this, I have added ADAL.js to my website, registered my website/webapp as Native Client in AAD. I am not sure about minimal amount of code to silently acquire the authentication token.

What are the minimum steps I need to do for getting an authentication token in vanilla JavaScript?

Note: I have gone through numerous sample on Azure AD auth on GitHub. But they all suggest to clone the repo and replace values for Audience, Tenants, etc. What I need is just a simple vanilla JS function to do the same without all the bloat code in those samples.

I have a vanilla JavaScript based web page. I need to call my web API at https://XYZ.azurewebsites which is secured using Azure Active Directory authentication.

For doing this, I have added ADAL.js to my website, registered my website/webapp as Native Client in AAD. I am not sure about minimal amount of code to silently acquire the authentication token.

What are the minimum steps I need to do for getting an authentication token in vanilla JavaScript?

Note: I have gone through numerous sample on Azure AD auth on GitHub. But they all suggest to clone the repo and replace values for Audience, Tenants, etc. What I need is just a simple vanilla JS function to do the same without all the bloat code in those samples.

Share Improve this question asked Aug 29, 2016 at 12:28 blackspacerblackspacer 3636 silver badges16 bronze badges 3
  • What do you mean by "silently acquire the authentication token". Do you mean you're trying to acquire a token without prompting the user to sign in? – Philippe Signoret Commented Aug 29, 2016 at 16:20
  • Can you also specify which samples you attempted to use? – Philippe Signoret Commented Aug 30, 2016 at 11:41
  • Hi, is it not possible to acquire token without prompting the user to login? – NatarajC Commented Feb 14, 2018 at 12:12
Add a ment  | 

1 Answer 1

Reset to default 6

One straight-forward approach to using ADAL.JS (and vanilla JavaScript):

  1. Configure the instance of AuthenticationContext.
  2. Use AuthenticationContext.login() to sign in.
  3. Use AuthenticationContext.handleWindowCallback() to handle token request responses.
  4. Use AuthenticationContext.acquireToken() to get an access token.
  5. Use the received access token to make your API requests.

Here's a full minimal example that obtains an access token to the Microsoft Graph API (an example of an API protected by Azure AD) and uses it to make an AJAX call to retrieve the signed-in user's profile. The numbers in the ments correspond to the steps above.

(I've also posted a Gist with a slightly more plete version which you can try out live.)

<html>
    <head>
        <title>Minimal sample using ADAL.JS</title>
        <script src="https://secure.aadcdn.microsoftonline-p./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.',
                        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./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>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论