[英]Salesforce OAuth with REST API using Javascript
我的 Salesforce 开发人员帐户中有一个应用程序,我想允许我的用户从我正在构建的远程应用程序访问它。 我看到我必须先使用 OAuth2.0 来授权我的用户,然后他们才能访问 salesforce 数据。 目前,我正在尝试使用salesforce 上描述的用户名-密码 OAuth 流程。
第 1 步)我通过以下代码片段使用用户名和密码请求访问令牌
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.
我看到一些消息来源(这里是这里)提到 Salesforce 不支持 CORS,应该使用另一种解决方案。 我见过的一些解决方案是 Salesforce APEX 代码、 AJAX 工具包或ForceTK 。
总之,我想看看(1)是否有一个简单的错误,我在上面的请求中是否犯了一个简单的错误来获取 OAuth access_token(2),或者我是否需要做一些不同的事情来获得访问权限(3)是否存在从我连接的应用程序登录用户并访问他们的 Salesforce 数据的更好方法是什么?
感谢所有和任何帮助!
您需要在自己的服务器上处理 OAUTH 部分。 这不仅仅是因为缺少 CORS,也没有办法完全在客户端安全地进行 OAUTH。 服务器真的可以是任何东西,但这里有一个使用 Play Framework 用 Java 编写的示例服务器,它也有一个 JavaScript / AngularJS 客户端: http : //typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
我在这里发布了对我有用的 ajax 代码,控制台中的这个 CORS 错误无关紧要。 如果您在网络中看到,您将获得访问令牌。 请参阅下面的ajax代码。
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
我希望这对你有用。
如果您从 Javascript 应用程序发出请求,我认为您需要在 CORS 设置中以及在 salesforce 中添加原始 URL/IP,以便它可以访问 salesforce 数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.