Reputation: 41
I'm trying to access onedrive through the API. I've managed to get an acces_token with files.readwrite scope. When i then try to access https://graph.microsoft.com/v1.0/me. It responds with the error "InvalidAuthenticationToken". What am i doing wrong
I've tried a bunch of different urls for example "https://graph.microsoft.com/v1.0/me/drive/root/children" and have searched stackoverflow, but nothing helped.
router.get('/response', function(req, res, next){
// already got code here.
var code = req.query.code
request.post({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
form: {
client_id: client_id,
redirect_uri: redirect_uri,
client_secret: client_secret,
code: code,
grant_type: 'authorization_code',
},
},function(error, response, body){
if (error){
console.log(error)
}
//so far so good. The access_token from the response looks okay and the
//scope is correct as well
request.get({
url: 'https://graph.microsoft.com/v1.0/me',
headers: {
'Authorization': "Bearer " + JSON.parse(body).access_token,
},
}, function(er, re, bo) {
//this response is an error message
console.log(bo)
});
});
})
I expected to get a request with information about the onedrive, but i got an error message.
Upvotes: 2
Views: 481
Reputation: 74
You aren't quite done yet with your authentication flow, the code you are getting back is an Authentication Code, not a Token. This is a very important distinction.
The first step in the oAuth code flow is getting the code, which you did. Then you need to 'trade' this code for an actual token. To do that you need to send another request to the server with this code and ask for your token. This request should go to a different URL. There is a lot of in depth explanation here for the flow you are using now https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
And here for the implicit flow, if you meant to use that instead: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
You might also want to look into using the AdalJS or preview MSAL.js library to handle a lot of the authentication for you, these are libraries made by Microsoft.
Upvotes: 1