【发布时间】:2014-09-21 04:32:46
【问题描述】:
我的 Salesforce 开发人员帐户中有一个应用程序,我想允许我的用户从我正在构建的远程应用程序访问。我看到我必须先使用 OAuth2.0 来授权我的用户,然后才能允许他们访问 salesforce 数据。目前我正在尝试使用salesforce 中描述的用户名密码 OAuth 流程。
第 1 步)我通过以下代码 sn-p 使用用户名和密码请求访问令牌
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username@location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
但是,我的请求失败并显示以下消息:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
我看到一些消息来源(here here here)提到,salesforce 不支持 CORS,应该使用另一种解决方案。我见过的一些解决方案是 Salesforce APEX 代码、AJAX toolkit 或 ForceTK。
总之,我想看看 (1) 我在上面的请求中是否犯了一个简单的错误来获取 OAuth access_token (2),或者我是否需要做一些不同的事情来获取访问权限 (3 ) 有没有更好的方法来登录用户并从我连接的应用程序访问他们的销售人员数据?
感谢所有帮助!
【问题讨论】:
-
您完全在前端实现
OAuth2.0的方法将始终面临CORS问题。 -
这个错误确实是因为不支持CORS。所以,你是对的,你需要以不同的方式处理它。你需要服务器端代码来处理这个。
-
是否有处理 Salesforce 服务器端 OAuth 的最佳方法? Salesforce APEX 代码或 AJAX 工具包?我尝试使用 [salesforce.stackexchange.com/questions/17382/… 示例)并收到“拒绝设置不安全标头“用户代理”消息。
-
AJAX 工具包是否可用于外部应用程序或仅可用于 VisualForce 页面?
标签: javascript ajax rest oauth salesforce