使用Javascript的REST API Salesforce OAuth

Jas*_*e17 6 javascript ajax rest oauth salesforce

我的salesforce开发人员帐户中有一个应用程序,我希望我的用户可以从我正在构建的远程应用程序中访问该应用程序.我发现在允许用户访问salesforce数据之前,我必须先使用OAuth2.0来授权我的用户.目前我正在尝试使用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
    }
});
Run Code Online (Sandbox Code Playgroud)

但是,我的请求失败了以下消息:

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. 
Run Code Online (Sandbox Code Playgroud)

我已经看到一些消息来源(这里这里)提到salesforce不支持CORS,应该使用另一个解决方案.我见过的一些解决方案是Salesforce APEX代码,AJAX工具包ForceTK.

总之,我希望看看(1)我是否有一个简单的错误,我正在使用我的上述请求来获取OAuth access_token(2)或者如果我需要做一些不同的事情来获取访问权限(3)从我的连接应用程序登录用户和访问其salesforce数据的更好方法?

所有和任何帮助表示赞赏!

Jam*_*ard 6

您需要在自己的服务器上处理OAUTH部分.这不仅仅是由于缺少CORS,也没有办法完全在客户端安全地使用OAUTH.服务器真的可以是任何东西,但这里是一个用Java编写的示例服务器,使用Play Framework,它还有一个JavaScript/AngularJS客户端:http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed


cki*_*ey3 3

您无法从 JavaScript 发出此请求。您需要发出服务器端请求。此流程有多种PHPC#Java等实现。