1

When I try to make a rest call from postman I am able to get access token but using ajax call I am getting 403 forbidden error. Appended https://cors-anywhere.herokuapp.com/ url to access token url to avoid CORS error.

  const formData = new FormData();
    formData.append("client_id", "client_id");
    formData.append("client_secret", "S7D7Q~excS5KjBh9JnPK-afZjTjtALGTKNweP");
    formData.append("grant_type", "client_credentials");
    formData.append("scope", "https://graph.microsoft.com/.default");
    $(document).ready(function () {
    requestToken();
   });
   var token;
function requestToken() {
  $.ajax({
    async: true,
    crossDomain: true,
    credentials: "include",
    url: "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/b262d1f3-4738-400d-ad54-c82cdabb6540/oauth2/v2.0/token", 
    method: "POST",
    headers: {
      "content-type": "application/x-www-form-urlencoded"
    },
    cache: false,
    processData: false,
    contentType: false,
    data: formData,
    success: function (response) {
      console.log(response);
      token = response.access_token;
    },
  });
}

Postman call is working I am able to get the access token

  • I agree with @juunas and what he mentioned msal.js is what you should use in your project and you may refer to [this answer](https://stackoverflow.com/a/65350674/14574199) or this [sample code](https://github.com/Azure-Samples/ms-identity-javascript-tutorial/tree/main/2-Authorization-I/1-call-graph) – Tiny Wang Sep 22 '21 at 06:40

1 Answers1

1

You should not use a client credential in your front-end. That's your application's password and will be visible to anyone visiting the page. Also if that is your actual secret in the question, you should remove it and create a new one.

This URL will not work:

https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/b262d1f3-4738-400d-ad54-c82cdabb6540/oauth2/v2.0/token

The reason you get a CORS error is because Azure AD is trying to prevent you from shooting your own foot. AAD sees the request and thinks it should not come from a browser front-end and thus denies it. The correct way to get the token is to use MSAL.js and acquire a token on behalf of the signed in user (delegated permissions).

juunas
  • 54,244
  • 13
  • 113
  • 149