We have implemented 2 OAuth flows between our app and SF where SF is auth provider - Web Server and Username and Password

Now we have use case where user is signed on SF and has to invoke our ASMX API. Is it possible to write in SF APEX page - generate for me access token for current session and environment and to send that automatically (in message header) when I call our API ? If not what is the best approach, I would like still to keep SF as Oauth provider, do not want to provide/issue access tokens from my side in this communication.

2 Answers 2


Sometime back, I was trying to connect 2 saleforce org via Oauth/Rest API. I think I did something similar. On Salesforce org(Source) act as auth provider. I created connected app in Target org to finally get the Oauth Token. providing small code base for that:

String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
// All of these u'll get once you set up connected app

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://login.salesforce.com/services/oauth2/token');//Note if my domain is set up use the proper domain name else use login.salesforce.com for prod or developer or test.salesforce.com for sandbox instance

    HttpResponse res = h.send(req);
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
    //RequestWrapper reqst=new RequestWrapper();

    if(objAuthenticationInfo.access_token!=null) // your check for access token

    { for any further Rest API call, I was using this, which I think you needed: 
      **req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);** 
      --------your further code------ }

Let me know in case you've any doubt over this :


Answer to your question, Yes!

You might not have any need to use any apex code but you can do it using javascript, and libraries that are Salesforce standard.

You can use sForce.js and/or jsForce - libraries from Salesforce

You can use the AJAX toolkit -

I cannot put the exact code for your requirement but these similar questions might give you an insight

Fetching records by using JQuery

Apex REST API call from Javascript via Ajax Toolkit

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .