Salesforce OAuth Username-Password Flow Integration: A Step-by-Step Guide

Salesforce OAuth Username-Password Flow Integration: A Step-by-Step Guide 

Introduction 

Salesforce OAuth 2.0 Username-Password Flow is a secure way to authenticate and allow API access without requiring user interaction. This approach is particularly useful when integrating Salesforce with third-party systems where user interaction is not possible, such as backend services or scheduled jobs. 

In this blog, we will go through:
✔️ Setting up OAuth in Salesforce
✔️ Creating a Connected App
✔️ Obtaining an Access Token
✔️ Making API Requests using OAuth 

 

  1. Setting Up OAuth in Salesforce

To implement OAuth authentication, you need two Salesforce organizations: 

  • Provider (Server) Org → training.batch01@vortexify.com 
  • Consumer (Client) Org → training.batch02@vortexify.com 

 

  1. Creating a REST Web Service in Salesforce (Provider Org)

We need to expose a RESTful web service in Salesforce, which the Consumer Org will access after authentication. 

Apex REST API Code (Provider Org) 

apex 

CopyEdit 

@RestResource(urlMapping=’/CaseManagerService/*’) 

global class CaseService { 

    @HttpGet() 

    global static Case getCaseRecordByID() { 

        // Retrieve Case ID from request parameters 

        Map<String, String> mapParams = RestContext.request.params; 

 

        Case caseRecord = [SELECT Id, Status, Priority, Type, Reason, Origin,  

                                    Subject, Description  

                           FROM Case  

                           WHERE Id =: mapParams.get(‘Id’)]; 

 

        return caseRecord; 

    } 

} 

📌 Salesforce REST API Endpoint:
https://ap16.salesforce.com/services/apexrest/CaseManagerService/?Id= 

 

  1. Creating a Connected App in Salesforce

A Connected App is required to generate an OAuth Client ID and Secret, which are needed to obtain an Access Token. 

Steps to Create a Connected App: 

  1. Go to Salesforce Setup 
  1. Navigate to:
    Setup → Apps → App Manager → New Connected App 
  1. Provide App Name, Description, and Callback URL 
  1. Enable OAuth Settings 
  1. Add OAuth Scopes:  
  • Full access (full) 
  • Perform requests on your behalf (refresh_token, offline_access) 
  1. Click Save 

🔹 Salesforce Generates: 

  • Client ID (Consumer Key) 
  • Client Secret (Consumer Secret) 

 

  1. Creating a Salesforce User with API Permissions
  1. Create a new user and assign it a profile with API permissions. 
  1. The user must have:  
  • Username (Email format) 
  • Password + Security Token 

🔹 Credentials to Share with the Client (Consumer Org): 

  • Client ID (Consumer Key) 
  • Client Secret (Consumer Secret) 
  • Username 
  • Password + Security Token 

 

  1. Obtaining an Access Token (Consumer Org)

The Consumer Org must authenticate using OAuth to get an Access Token. 

Pre-Requisite: Add Remote Site Settings 

Before making an API call, add the Provider’s URL to Remote Site Settings in the Consumer Org. 

OAuth Token Request (Consumer Org) 

📌 Authorization Server Endpoint:
https://login.salesforce.com/services/oauth2/token 

Make an HTTP POST Request 

http 

CopyEdit 

POST https://login.salesforce.com/services/oauth2/token 

Content-Type: application/x-www-form-urlencoded 

 

grant_type=password& 

client_id=YOUR_CLIENT_ID& 

client_secret=YOUR_CLIENT_SECRET& 

username=YOUR_USERNAME& 

password=YOUR_PASSWORD 

🔹 Response: If successful, Salesforce returns an Access Token. 

 

  1. Using the Access Token to Access Salesforce API

Once the Consumer Org gets an Access Token, it can make an API request to Salesforce. 

API Request to Fetch Case Details 

📌 Endpoint:
https://ap16.salesforce.com/services/apexrest/CaseManagerService/?Id=CASE_ID 

Apex Code (Consumer Org) to Fetch Case Details 

apex 

CopyEdit 

public class CaseAPIClient { 

    public static String getCaseDetails(String caseId, String accessToken) { 

        String endpointURL = ‘https://ap16.salesforce.com/services/apexrest/CaseManagerService/?Id=’ + caseId; 

         

        HttpRequest req = new HttpRequest(); 

        req.setEndpoint(endpointURL); 

        req.setMethod(‘GET’); 

        req.setHeader(‘Authorization’, ‘OAuth ‘ + accessToken); 

 

        Http http = new Http(); 

        HttpResponse res = http.send(req); 

 

        return res.getBody(); // JSON Response 

    } 

} 

 

  1. Visualforce Page to Display Case Details (Consumer Org)

VF Page Code: 

html 

CopyEdit 

<apex:page controller=”ShowCaseDetailsController”> 

    <apex:form > 

        <apex:pageBlock title=”Case Details”> 

            <apex:inputtext value=”{!caseRecordID}” placeholder=”Enter Case ID”/> 

            <apex:commandButton value=”Get Details” action=”{!getCaseDetails}” rerender=”caseBlock”/> 

        </apex:pageBlock> 

         

        <apex:pageBlock title=”Case Information” id=”caseBlock”> 

            <apex:outputLabel>Case ID: {!CaseID}</apex:outputLabel><br/> 

            <apex:outputLabel>Case Number: {!CaseNumber}</apex:outputLabel><br/> 

            <apex:outputLabel>Case Status: {!CaseStatus}</apex:outputLabel><br/> 

        </apex:pageBlock> 

    </apex:form> 

</apex:page> 

 

  1. Benefits of OAuth Username-Password Flow in Salesforce

✔️ No User Interaction Needed → Ideal for backend services
✔️ Secure Authentication → Uses OAuth 2.0
✔️ Seamless API Access → Obtain and use Access Tokens
✔️ Easy Implementation → No need for user login 

 

  1. Conclusion

Salesforce OAuth Username-Password Flow allows seamless API integration without user interaction. By following these step-by-step instructions, you can successfully:
Create a Connected App
Obtain an Access Token
Make API calls to Salesforce 

 

Leave a Comment

Your email address will not be published. Required fields are marked *