Not getting API token

import { fetch } from '@forge/api';

const tenantId = '/oauth2/token';
const clientId = 'clientId';
const clientSecret = 'clientSecret';
const resourceUri = 'https://graph.microsoft.com';

async function getToken() {
  const url = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;

  const params = new URLSearchParams();
  params.append('client_id', clientId);
  params.append('client_secret', clientSecret);
  params.append('scope', `${resourceUri}/.default`);
  params.append('grant_type', 'client_credentials');

  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: params.toString(),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Failed to fetch token: ${response.status} - ${errorText}`);
  }

  const data = await response.json();
  return data.access_token;
}

export { getToken };

when I am running this code in forge react I am getting this message
Refused to connect to ‘https://login.microsoftonline.com/1233/oauth2/token/oauth2/v2.0/token’ because it violates the following Content Security Policy directive: “connect-src ‘self’ https://api.atlassian.com/metal/ingest

Hi @JainDivyanshu, you mentioned that this code is running in a React front-end app. If so, you will need to define external egress permissions; please have a look at this page.
In addition, the forge/api package is meant for Forge resolvers; you don’t need to use it for your front-end app.

image
Hi @BoZhang
I already defined permission but not running

If you’re calling it from the frontend it needs to be:

permissions:
  external:
    fetch:
      backend:
        - '...'
      client:
        - '*.microsoftonline.com'
        - 'graph.microsoft.com'
2 Likes

I want token from GET method API from Microsoft Graph API. I need the code when I am passing tenant id, client Secret, client Id and resource URL. after I deploy the code in forge app. I want in forge app.