Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Salesforce by (11.9k points)

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.

Step 1) I request an access token using username and password via the below code snippet

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', '[email protected]'),

        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

    }

});

My request, however, is failing with the following message:

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. 

I have seen some sources (here here here) mention that CORS is not supported in salesforce and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.

In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to log in users and access their salesforce data from my connected app?

All and any help is appreciated!

1 Answer

+1 vote
by (32.1k points)

For this, you'll need to handle the OAuth part on your server. This isn't certainly due to the lack of CORS, but there is also no way to securely use OAuth purely on the client-side.

To learn in-depth about Workflow in Salesforce, sign up for an industry based Salesforce Course.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...