How to get Microsoft Graph API Access token from Node Script?

后端 未结 3 672
别那么骄傲
别那么骄傲 2020-12-10 19:49

I\'d like to use this library to interact with the graph API for my AD - https://github.com/microsoftgraph/microsoft-graph-docs/blob/master/concepts/nodejs.md

Howeve

3条回答
  •  醉话见心
    2020-12-10 20:24

    To run a back-end non-user-authenticated daemon connected to the Graph API, you want to use the app-only authentication flow. Here's a quick summary of the official steps:

    1. Create your Azure AD Tenant. Note the yourtenant.onmicrosoft.com name, and copy this value down.
    2. Register an application through the global Azure Active Directory blade's App Registrations section, not directly within the tenant properties. Copy the Application ID; we'll need it later.
    3. Create a key tied to the registration and remember to copy it down. Once you click out, you can't get the key value back, so make sure to copy it.
    4. Also update the registration's permissions to what you need, click Save, and then also hit the Grant Permissions button.
    5. Make an HTTP request to the login.microsoftonline.com domain to obtain an access token.
    6. Use the access token to make Graph API requests.

    Here's a link to Microsofts Node.js example, and here's a link to the direct documentation on the HTTP call to make to retrieve an access token. And here's a super stripped-down example that will output the retrieved access token. Replace the [Tenant], [ApplicationID], and [Key] values:

    const request = require("request");
    
    const endpoint = "https://login.microsoftonline.com/[Tenant].onmicrosoft.com/oauth2/token";
    const requestParams = {
        grant_type: "client_credentials",
        client_id: "[ApplicationID]",
        client_secret: "[Key]",
        resource: "https://graph.windows.net"
    };
    
    request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
        if (err) {
            console.log("error");
        }
        else {
            console.log("Body=" + body);
            let parsedBody = JSON.parse(body);         
            if (parsedBody.error_description) {
                console.log("Error=" + parsedBody.error_description);
            }
            else {
                console.log("Access Token=" + parsedBody.access_token);
            }
        }
    });
    

    Once we have the access_token, we can call out to the Graph API. Assuming the apps permissions were configured correctly and applied from step #4, we can start making Graph API requests:

    function testGraphAPI(accessToken) {
        request.get({
            url:"https://graph.windows.net/[Tenant]/users?api-version=1.6",
            headers: {
              "Authorization": accessToken
            }
        }, function(err, response, body) {
            console.log(body);
        });
    }
    

提交回复
热议问题