XMehdi01
XMehdi01

Reputation: 1

SharePoint cannot get Access Token with JavaScript?

I need to get access token from SharePoint, In order to upload some files! I got access token from postman successfully, But when I try to do the same request with Javascript!

const generateToken = async () => {
  const headers = { "Content-Type": "application/x-www-form-urlencoded" };
  var formdata = {};
  formdata["grant_type"] = "client_credentials";
  formdata["client_id"] = "<client_id>";
  formdata["client_secret"] = "<client_secret>";
  formdata["resource"] =
    "00000003-0000-0ff1-ce00-000000000000/site_url@tenant_id";
  const body = Object.keys(formdata)
    .map((key) => `${key}=${formdata[key]}`)
    .join("&");
  var requestOptions = {
    method: "POST",
    headers,
    body,
  };
  await fetch(
    "https://accounts.accesscontrol.windows.net/<tenant_id>/tokens/OAuth/2",
    requestOptions
  )
    .then((response) => response.json())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};
generateToken();

when I execute the page which have this script I got this error

error TypeError: Failed to fetch
    at generateToken

But IDK why the respose status is 200 OK, without returning body which contain access_token

enter image description here

Any help is much appreciated!

Upvotes: 0

Views: 620

Answers (1)

stackozaurus
stackozaurus

Reputation: 146

You cannot get the token from javascript like that, only from single page applications because of the security issues: you expose your client secret.

You can use Microsoft Authentication Library (MSAL) for JS instead.

Upvotes: 1

Related Questions