I am working on a nodejs app using jsforce to authenticate users their Salesforce org with nodejs app and this is how it works at high level:
- User launches nodejs app and login screen is shown with two
buttons:
- Login to Production Org
- Login to Sandbox Org
- User is redirected to login.salesforce.com or test.salesforce.com depending on which button was clicked.
- User logins and approves the connected app and callback url is invoked with auth code.
- Now I am confused if user did the authentication from a Production org or Sandbox org. I need that information to authorize my app.
I need this information so that I can properly set loginUrl
property when creating oauth2 object for jsforce(refer to the below code).
One option I can see is depend on the referrer
header of request when callback url is invoked but there might be better options? Is there a better alternative?
NOTE: If i default loginUrl to login.salesforce.com and user is authenticating sandbox org, I am getting invalid_grant
error.
const jsforce = require("jsforce");
const app = express();
// Callback function to get Auth Token
app.get('/oauth2/callback', (req, res) => {
const oauth2 = new jsforce.OAuth2({
loginUrl: 'https://login.salesforce.com',
clientId: 'SALESFORCE_CLIENT_ID',
clientSecret: 'SALESFORCE_CLIENT_SECRET',
redirectUri: 'http//localhost:3001/oauth2/callback',
});
const conn = new jsforce.Connection({ oauth2: this.oauth2 });
const { code } = req.query;
conn.authorize(code, (error) => {
if (error) {
console.error("Failed to authorize request with provided authentication code");
return;
}
console.error("authorize worked successfully");
res.redirect("/");
});
});