function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ArpitArpit 

Using rest api with Web Server OAuth Authentication Flow

Hi,

I have a requirement where i need to send data from one sales force ORG to other Sales force ORG using rest api.

But here in this i want to use Web Server OAuth Authentication Flow for providing authentication for this.

I need help in this on how to get it started.If someone can post some demo code for this then that will help a lot.

I am having Client ID,Secret ID and redirect_uri that we requires but i am facing issue in generating Token within my apex class and fetch and use that token so that i can move ahead.

Any help on the same is Highly Appreciated.Looking ahead for an Quick response.

Thanks in Advance !!

Arpit
logontokartiklogontokartik
I am assuming you are clicking a button on a page to connect to another Salesforce Org.  Here is what you might need to do.

When user clicks a button - call this method in apex controller 

public Pagereference validateUserCredentials(){
      		
      		
 Pagereference OAuthPage = new Pagereference(oSettings.OAuthURL__c + '&client_id='+oSettings.ClientId__c+'&redirect_uri='+oSettings.RedirectURI__c);
      		
     return OAuthPage;
      		
      		        
}

In your Apex page, add an action method, something like this (see how OAuthAccess method is listed)

<apex:page controller="OAuthPage" showHeader="false" sidebar="false" standardStyleSheets="false" doctype="html-5.0" action="{!OAuthAccess}">

In your Apex controller define OAuthAccess like below

public Pagereference OAuthAccess() {
    	
    	if(Apexpages.currentPage().getParameters().get('code') == null){
      		
      		return null;
      		
      	}else {
      		
      	    String code = Apexpages.currentPage().getParameters().get('code');
            Httprequest req = new HttpRequest();    
            req.setMethod('POST');    
            req.setHeader('Content-Type','application/x-www-form-urlencoded');
            
            String ClientId = oSettings.ClientId__c;
            String ClientSecret = oSettings.ClientSecret__c;           
                     
            req.setBody('grant_type=authorization_code' + 
                  '&code=' + code + 
                  '&client_id=' + ClientId + 
                  '&client_secret=' + ClientSecret + 
                  '&redirect_uri='+oSettings.RedirectURI__c);     
            
            req.setEndpoint(oSettings.Endpoint__c);         
            Http http = new Http();
            HttpResponse res;
            
            system.debug(res);
            
            try {
              	res = http.send(req);                
                system.debug(res.getBody());
                ResponseClass resp = (ResponseClass)JSON.deserialize(res.getBody(),ResponseClass.class);
                sessionId    	   = resp.access_token;
                instanceURL  	   = resp.instance_url;
                
            }catch(system.CalloutException e){
              messages.add(e.getMessage());	
            }
        	
        	if(res.getStatusCode() > 300){
        		messages.add('Error in Authentication ' + res.getStatus() + ' ' + res.getBody());	
            	return null;
            
            }
        	
        	messages.add('Authentication Successful');
        	
        	isAuthenticated = true;
        	
      		return null;
    	
    }

The Response Class is where you have the instance uRl and the session Id that you can use in subsequent calls.

public class ResponseClass {
    
        public String id {get;set;}
        public String access_token {get;set;}
        public String instance_url {get;set;}
        
    
    }

Hope this helps.. 




ArpitArpit
Hi Kartik,

Thanks for your quick reply


I have tried already what you mention in above code The issue is that when i am trying to give the "Pagereference OAuthPage = new Pagereference(oSettings.OAuthURL__c + '&client_id='+oSettings.ClientId__c+'&redirect_uri='+oSettings.RedirectURI__c);" URL in my page reference i am not recieving token in Oauth Access method and only getting same URL in debug log but when i am trying the same from UI then i cann see the code in URL but unable to fetch that   in my class.

Can you please help me with this?

Thanks.
Arpit
logontokartiklogontokartik
HI Arpit,

Hmm. that code in URL is a URL Parameter, so you need to do Apexpages.currentPage().getParameters().get('code'). But you might have already done this. Did you setup the method as part of <apex:page> ? 

If possible can you post your code so that I can see where its going wrong?

ArpitArpit
Hi,

Thanks for all your support.

Now i am facnig the issue after i get Access token and send the data by having that in setheader.

I am getting response error of 401 saying that Session is Invalid.Can you please help me with the same?

Looking for quick response

Thanks.
Arpit