Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So I am trying to get the auth token and authenticate salesforce api endpoint

where i try to use axios and fetch 

i made a function to get post it to the api end point to get the response 
sample response is 

```
{
  "access_token": "00DR00000008oBT!AQwAQCPqzc_HBE59c80QmEJD4rQKRRc1GRLvYZEq...",
  "instance_url": "https://MyDomainName.my.salesforce.com",
  "id": "https://login.salesforce.com/id/00DR00000008oBTMAY/005R0000000IUUMIA4",
  "token_type": "Bearer",
  "issued_at": "1513887500425",
  "signature": "3PiFUIioqKkHpHxUiCCDzpvSiM2F6//w2/CslNTuf+o="
}
```


Link for salesforce api 
https://developer.salesforce.com/docs/atlas.en-us.api_iot.meta/api_iot/qs_auth_access_token.htm


then i am trying to pass the auth  to get the token and fetch to the endpoint to authenticate 

and API gave below example on how to approach 

The access_token field in the response contains the access token value. API clients pass the access token in the Authorization header (Authorization: Bearer access_token) of each request.

Use the instance_url field value in the response as the Salesforce instance URL in your REST API resource URIs (for example, instance_url/services/data/v42.0/iot/orchestrations).

can anyone give there peace of mind on how to further solve the problem  to finish authentication ?


What I have tried:

authentication ?
```
const auth = ()=>{
    

    axios.post (`${endpoint}/services/oauth2/token`,{
    body:`grant_type = password&client_id=${clientId}&
    client_secret=${clientSecret}&
    username=${username}&
    password=${password}`,
    headers: {
        "Authorization": 'Basic' + Buffer.from(`${client_Id}:${clientSecret}`).toString('base64'),
        "Content-Type": "application/x-www-form-urlencoded",
    }
})
.then(res => res.json())
.then(json => {
    console.log('fetching token')
    console.log(res)
    return json;
}).catch(error => console.log(error));

return [res.access_token, res.instance_url];
}


const salesforce=( res)=>{

    const token = auth(config);

    const instanceToken =token[0];
    const instance_url= token[1];

    return fetch(`{}`)
    

}
Posted
Updated 11-Apr-22 0:57am

1 solution

You haven't really explained what the issue is but I'm going to assume that it's because the access token and instance URL aren't being returned correctly from the auth() method. This is because the authentication is using an XML HTTP request which relies on the Javascript promises API.

What's happening is you're calling the auth() method which starts the axios.post() which you can see is returning a promise, you're then subscribing to that promise to get the access token and instance URL, but you're returning from the auth() method before that promise has had chance to complete. When the method returns, it doesn't know what the res variable is.

You need to adjust your code to return the promise from the auth() method and then subscribe to the result. Something similar to:

JavaScript
const auth = ()=>
  return axios.post(`${endpoint}/services/oauth2/token`,{
    body:`grant_type = password&client_id=${clientId}&
    client_secret=${clientSecret}&
    username=${username}&
    password=${password}`,
    headers: {
        "Authorization": 'Basic' + Buffer.from(`${client_Id}:${clientSecret}`).toString('base64'),
        "Content-Type": "application/x-www-form-urlencoded",
    }
  })
  .then(res => res.json())
  .then(json => {
    console.log('fetching token')
    console.log(res)
    return json;
  })
  .catch(error => console.log(error));
}

const salesforce=( res)=>{

  // Here we subscribe to the result of the authentication instead
  // of relying on the return value, which should ensure this code
  // executes on the response has been returned
  auth(config).then(response => {

    // Here we can access the token and instance URL from the response
    const instanceToken = response.access_token;
    const instance_url= response.instance_url;

    return fetch(`{}`)
  });

}


Another way would be to make your methods use async and await which lets your bypass some of the headaches. For example:

JavaScript
const auth = async () => {
  try {
    const response = await axios.post(..);
    return response ? response.json() : undefined;
  } catch (err) {
    console.error(err);
    return undefined;
  }
}

const salesforce = async (res) => {
  const response = await auth();

  if (response) {
    const access_token = response.access_token;
    const instance_url = response.instance_url;
  }
};
 
Share this answer
 
Comments
harsha 4 11-Apr-22 7:05am    
@Chris Copeland thanks for the approach

My problem there i asked was, even if i get the url and access token , how do I use them to make a req and hit api in order to successfully pass the req to authorize.

How can i make use of fetch to send the token that i get?

according to this
"The access_token field in the response contains the access token value. API clients pass the access token in the Authorization header (Authorization: Bearer access_token) of each request.

Use the instance_url field value in the response as the Salesforce instance URL in your REST API resource URIs (for example, instance_url/services/data/v42.0/iot/orchestrations)."
Chris Copeland 11-Apr-22 8:05am    
You've already written code to do the initial authentication, so the remaining process should be easy? You have the access token and the URL, so you just need to build the URL using the instance_url variable (ie. ${instance_url}/services/data..) and pass in the token to the header like you did with the client ID and secret (ie. headers: { "Authorization": `Bearer ${access_token}` })
harsha 4 11-Apr-22 8:07am    
thanks for that man, you legend
I know to build url but i am constructing it wrong
thanks for the help
More power to you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900