Tell me more ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have created a GET method REST service and trying to Ajax call the service through sforce.connection.remoteFunction from JavaScript. Able to get the Session Id and it hitting the service. But the response was Error 401 Unauthorized. Is there anything I'm missing in the request?

Note: I'm Passing the session Id in the request header.

Attaching my Script:

<script type="text/javascript">
window.onload = setupPage;

function setupPage() {
var result = sforce.connection.login("myloginmailid", "pwd+security token"); 
sforce.connection.init(result.sessionId, 'Service URL'); 
    <!-- Salesforce Remote Connection-->  

    sforce.connection.remoteFunction({
        url : "Service URL",
        requestHeaders: {"Authorization":"Bearer"+__sfdcSessionId, "Content-Type":"application/json", "Connection":"Keep-Alive" },
        method: "GET",
        onSuccess : function(response) {
              alert("Success" +response);  
           },
       onFailure : function(response) {
              alert("Failed" + response)
          }
   });    
</script>
share|improve this question
 
Did you setup OAuth? –  erbdex Sep 27 at 9:52
 
@erbdex I added the domain name "ap1.salesforce.com/"; in Remote Settings.Got the session Id through "sforce.connection.login" method. –  Dinesh Sep 27 at 9:55
 
@Dinesh can you post the script you tried ? –  regal Sep 27 at 9:59
 
@responsive Attached my script. Is there anything I'm missing in request? "__sfdcSessionId" is the session id i got through these script, <script type="text/javascript"> var __sfdcSessionId = '{!GETSESSIONID()}'; </script> –  Dinesh Sep 27 at 10:15
 
You can just set the session ID directly: sforce.connection.sessionId = __sfdcSessionId. –  sfdcfox Sep 27 at 14:21
add comment

2 Answers

First thing I am seeing is you are missing space between Bearer and __sfdcSessionId. Add space and try it

requestHeaders: {"Authorization":"Bearer<addSpace>"+__sfdcSessionId, "Content-Type":"application/json", "Connection":"Keep-Alive" },

share|improve this answer
 
I added space between Bearer and my session id , It's not working –  Dinesh Sep 27 at 10:45
add comment
up vote 2 down vote accepted

Finally i got the solution,

  1. In the sforce.connection.init method we have to pass the "current Session Id" of the organization from which we are requesting,
  2. As responsive mentioned provide space between Bearer and session id.

Changed line of code:

sforce.connection.init(__sfdcSessionId, 'Service URl');

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.