Search code examples
microsoft-graph-apiazure-ad-msalazure-oauth

MSAL - Network request failed. Please check network trace to determine root cause


I am trying to use MSAL for node.js for OAuth 2.0 authentication, and I'm getting an error when calling acquireTokenByAuthCode.

Network request failed. Please check network trace to determine root cause. | Fetch client threw: Error: HTTP status code 400 | Attempted to reach: https://login.microsoftonline.com/{myTenantId}/oauth2/v2.0/token

Client instance:

const msal = new ConfidentialClientApplication({
    auth: {
        clientId: process.env.MS_CLIENT_ID,
        clientSecret: process.env.MS_SECRET,
        authority: process.env.MS_AUTHORITY
    }
})

Login route:

const uri = await msal.getAuthCodeUrl({
  responseMode: 'query',
  redirectUri: `${process.env.APP_URI}/auth/code`,
  scopes: ['user.read']
});
res.redirect(uri);

Token route (/auth/code):

try {
  const {
    accessToken,
  } = await msal.acquireTokenByCode({
    scopes: ['user.read'],
    code: req.query.code,
    redirectUri: `${process.env.APP_URI}/auth/code`,
  });
  res.cookie('token', accessToken);
  res.redirect('/');
}
catch(e) {
  res.status(401).send(e);
}

I can retrieve an auth code just fine, but I get the error when trying to get the token in the last snippet.


Solution

  • I fixed it. The Application was just missing the openid permission.