Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

node.js - How to get Microsoft Graph API Access token from Node Script?

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

However, all of the existing javascript libraries I've found to return access tokens expect a return URL to be passed in, as well as some other web-specific stuff, leading me to believe this is some kind of requirement on Microsoft's end.

Is there any good way to authenticate/receive an access token while running a backend node script (nothing web related) so that I can begin to make calls against the Microsoft Graph API? Thanks in advance for the advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

BU0's answer didn't work correctly for me because Microsoft changed their way of using the graph API so I wasn't able to get all the data I needed. Here's how I did it using BU0 answer and this tutorial:

const request = require("request");

const endpoint = "https://login.microsoftonline.com/[Tenant]/oauth2/v2.0/token";
const requestParams = {
    grant_type: "client_credentials",
    client_id: "[ApplicationID]",
    client_secret: "[Key]",
    scope: "https://graph.microsoft.com/.default"
};

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);
        }
    }
});

function testGraphAPI(accessToken) {
    request.get({
        url:"https://graph.microsoft.com/v1.0/users",
        headers: {
          "Authorization": "Bearer " + accessToken
        }
    }, function(err, response, body) {
        console.log(body);
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...