OAuth 2.0 Web Server Flow for Web App Integration (SFDC, Salesforce)

Problem: User want to create contact in one salesforce org from another salesforce org and as a web developer we don’t want to expose user’s credentials to the web application otherwise owner of the web app/hacker may misuse this information if web application is not much secure.

Solution: We will use web server flow in which user can enter credentials on the fly using standard salesforce login screen thereby not exposing his credentials to the web application.

Prerequisite:

In this vedio, I will be explaining the steps for getting access token using web server flow.

Now once we gone through all the steps mentioned in the vedio, we will be creating contact in another org using web server flow. So, in actual we will do the following-

  • Creating a connected app in target org(Please refer this article to setup connected app for web server flow)
  • Creating remote site setting for target org (in which you want to create case)
  • Creating Visualforce page and Apex where we will create three buttons 1) to get authorization code, 2) to get access token using authorization code and then 3) creating case using access token.

WebServerFlowPage (Visualforce Page)

<apex:page controller="WebServerFlowController">
    <apex:messages />
    <apex:form >
        <apex:commandButton action="{!getAuthCode}" value="getAuthCode" id="theButton"/>  
        <apex:commandButton action="{!getAccessToken}" value="getAccessToken" id="theButton1"/>
        <apex:commandButton action="{!createContact}" value="createContact" id="theButton2"/>   
    </apex:form>
</apex:page>

AccessTokenWrapper (Apex Class)

public class AccessTokenWrapper{
    public String access_token; 
    public String refresh_token;
    public String signature; 
    public String scope;   
    public String instance_url; 
    public String id;  
    public String token_type;   
    public String issued_at;   
    public static AccessTokenWrapper parse(String json){
        return (AccessTokenWrapper) System.JSON.deserialize(json, AccessTokenWrapper.class);
    }
}

WebServerFlowController (Apex Class)

public class WebServerFlowController  {

    //Use your Client Id
    String clientId = '****';

    //Use your Client Secret
    String clientsecret='****';

    String accesstoken_url='https://login.salesforce.com/services/oauth2/token';

    String authurl='https://login.salesforce.com/services/oauth2/authorize';
    
    String creationEndPoint ='/services/data/v49.0/sobjects/Contact';

    String redirect_uri = 'https://sandeepcompany2-dev-ed--c.visualforce.com/apex/WebServerFlowPage'; //This is callback url
    
    String access_token;
    String instance_url;
    
    public PageReference getAuthCode() {
        PageReference pageRef = new PageReference(authurl + '?response_type=code&client_id='+clientId+'&redirect_uri='+redirect_uri);
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public WebServerFlowController () {
        
    }
    
    public PageReference getAccessToken() {
        Http h= new Http();
        String code = ApexPages.currentPage().getParameters().get('code');        
        HttpRequest req= new HttpRequest();
        String reqbody = 'code=' + code + '&grant_type=authorization_code&client_id='+clientId+'&redirect_uri='+redirect_uri+'&client_secret='+clientsecret;
        
        req.setBody(reqbody);
        
        req.setMethod('POST');
        
        req.setEndpoint(accesstoken_url);
        
        HttpResponse res=h.send(req);
        
        AccessTokenWrapper obj = AccessTokenWrapper.parse(res.getBody());
        access_token = obj.access_token;
        instance_url = obj.instance_url;
        apexpages.addMessage(new ApexPages.message(Apexpages.Severity.INFO, res.getBody()));
        return null;
    }
    
    public PageReference createContact() {
        Http h2 = new Http();
        String jsonstr = '{"FirstName": "Sandeep", "LastName" : "Kumar ' + System.now() + '"}';
    
        HttpRequest req1 = new HttpRequest();
    
        req1.setHeader('Authorization','Bearer ' + access_token);
    
        req1.setHeader('Content-Type','application/json');
    
        req1.setHeader('accept','application/json');
    
        req1.setBody(jsonstr);
    
        req1.setMethod('POST');
    
        req1.setEndpoint(instance_url + creationEndPoint);
    
        HttpResponse res1 = h2.send(req1);
        apexpages.addMessage(new ApexPages.message(Apexpages.Severity.INFO, res1.getBody()));
        return null;
    }
}

Demo

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply