NodeJS集成Salesforce认证报错invalid_grant,求排查帮助
Salesforce密码认证报错:Error: invalid_grant - authentication failure排查
我正尝试在NodeJS应用中实现Salesforce认证,目前遇到错误:Error: invalid_grant - authentication failure。请问我遗漏了哪些配置?是否需要在Salesforce端进行额外设置?以下是我的代码,恳请帮忙排查问题:
代码示例
app.js
var nforce = require('nforce'); const client_id = '**' const client_secret = '****' const redirect_uri = 'https://***.sandbox.my.salesforce.com/services/oauth2/success' const sfdc_user = '*****' const sfdc_pass = '***' const credentials = { client_id :client_id, client_secret:client_secret, grant_type:"password", username:sfdc_user, password:sfdc_pass } async function getConnection(){ const loginUrl = "https://***.sandbox.my.salesforce.com/services/oauth2/token"; var org = nforce.createConnection({ clientId: credentials.client_id, clientSecret: credentials.client_secret, redirectUri: redirect_uri, }); console.log('org >>'+JSON.stringify(org)); let oauth= await org.authenticate({ username: credentials.username, password: credentials.password}); console.log('oauth >>'+oauth); //Couldnt get this console const access_token = oauth.access_token; const sf_auth_url = oauth.instance_url + '/services/data/v48.0/' sf_auth = { 'Authorization':'Bearer ' + access_token, 'Content-type': 'application/json', 'Accept-Encoding': 'gzip' } return { sf_auth,sf_auth_url } } module.exports = { getConnection }
main.js
const f = require('./app'); const https = require('https') const fs = require('fs') const port = 3000 const server = https.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/html'}) res.end(); }) server.listen(port,function(error){ if(error){ console.log('Something Went Wrong!') }else{ console.log('Server is listening on port '+port) f.getConnection(); } })
排查要点
一、Salesforce端配置检查
- 开启Connected App的密码授权类型:进入Setup → App Manager → 找到你的Connected App → 编辑OAuth设置,确保勾选**"Resource Owner Password Credentials"**
- 验证用户账号有效性:
- 账号未锁定、未过期
- 关联的Profile/Permission Set已开启**"API Enabled"**权限
- 密码需包含安全令牌:若服务器IP不在Salesforce信任IP列表中,必须使用
密码+安全令牌拼接作为认证密码(比如密码123456+令牌ABCDE,则传入123456ABCDE) - 检查IP限制:Connected App的IP限制需包含你的NodeJS服务器IP,或暂时关闭IP限制测试
- 确认环境一致性:Connected App和用户账号都属于当前使用的Sandbox环境
二、代码端优化与检查
- 移除冗余参数:密码认证无需
redirectUri,从nforce.createConnection中删除该参数 - 指定登录地址:在
authenticate方法中明确传入Sandbox的登录URL,避免自动路由错误:let oauth = await org.authenticate({ username: credentials.username, password: credentials.password, loginUrl: 'https://test.salesforce.com' // 或你的自定义Sandbox域名 }); - 添加错误捕获:在
getConnection中加入try/catch,打印完整错误信息:async function getConnection(){ try { // 原有代码逻辑 } catch (err) { console.error('认证错误详情:', err.message, err.response?.body); } } - 校验变量正确性:确认
credentials.username和credentials.password赋值正确,无拼写错误
内容的提问来源于stack exchange,提问作者user19160217
相关产品推荐
相关产品推荐

