1

I have a backend in Nodejs using Axios for my API calls. I need to implement Azure Authentication to get a token so I followed the sample below:

https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-nodejs-webapp-msal?WT.mc_id=Portal-Microsoft_AAD_RegisteredApps

The sample uses express and has redirects to first get and authorization and then a token, I have been trying to find a sample with Axios however I couldn't find one.

This is what I have so far, the idea is using the result to get a token,any guidance is much appreciate it.

const msal = require('@azure/msal-node');


const REDIRECT_URI = "http://localhost:3000/";
const LOGIN = "https://login.microsoftonline.com/";


const config = {
    auth: {
        clientId: "12345678910",
        authority: "https://login.microsoftonline.com/12345678910",
        clientSecret: "Secret",
        knownAuthorities: ["https://login.microsoftonline.com/12345678910"
    ]
    }
};

const pca = new msal.ConfidentialClientApplication(config);

module.exports = {

    async getAzureAdToken(){

        try {

            let instance = axios.create({baseURL: LOGIN});
            
            const authCodeUrlParameters = {
                scopes: ["user.read"],
                redirectUri: REDIRECT_URI
            };

            pca.getAuthCodeUrl(authCodeUrlParameters).then((response) =>{

                let url = response.substring(LOGIN.length);

                instance.get(url).then((result) =>{


                });

            }).catch((error) => console.log(JSON.stringify(error)));
        } catch (error) {
            throw error
        }
    },
Classic
  • 23
  • 2
  • 4

1 Answers1

4

You could use client credentials flow to get access token with axios. Client credentials flow permits a web service (confidential client) to use its own credentials, instead of impersonating a user, to authenticate when calling another web service. In the client credentials flow, permissions are granted directly to the application itself by an administrator. We need to add application permissions in API Permission.

Test in Postman:

POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id=<client_id>
&scope=https://graph.microsoft.com/.default
&client_secret=<client_secret>
&grant_type=client_credentials

Code using Nodejs:

// Replace these values from the values of you app
const APP_ID = '[APP_ID/CLIENT_ID]';
const APP_SECERET = '[CLIENT_SECRET]';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/[TENANT_ID]/oauth2/v2.0/token';
const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';

const axios = require('axios');
const qs = require('qs');

const postData = {
  client_id: APP_ID,
  scope: MS_GRAPH_SCOPE,
  client_secret: APP_SECERET,
  grant_type: 'client_credentials'
};

axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

let token = '';

axios
  .post(TOKEN_ENDPOINT, qs.stringify(postData))
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
unknown
  • 6,778
  • 1
  • 5
  • 14
  • If my reply is helpful, please accept it as answer, thank you. – unknown Apr 09 '21 at 01:57
  • Hi, I was able to get an access token using the example above, however I cannot use the token to call Microsoft Graph and get user information. When I try to do that I get the following: Insufficient privileges to complete the operation. Do I need to use another type of authentication flow? I need both client credentials and user information. – Classic Apr 09 '21 at 21:07
  • Hi, @Classic. Could you share your api permissions in the portal? We usually add `User.Read.All` of application permission in Microsoft Graph API. And don't forget to grant admin consent for your tenant. – unknown Apr 11 '21 at 12:47
  • Hi Pamela I checked the portal and permissions are set. – Classic Apr 12 '21 at 03:21
  • I used the single page app sample code to test getting user profile and it worked. I noticed the JavaScript uses a login method that takes an array of scopes which I don't do in my code. I looked at the @azure/msal code and couldn't find something similar. – Classic Apr 12 '21 at 03:33
  • But the code uses client credentials flow which needs **application permission** in my reply. Single page app uses delegated permission. – unknown Apr 12 '21 at 06:51