Sunday, August 23, 2020

OAuth 2.0 Username-Password Flow In Salesforce

We can use Username-Password flow to allow the external system to authorize using connected app however this mechanism is not recommended since it passes credentials back and forth.


For an external application that needs to authenticate with salesforce we need to create a connected app so as to inform salesforce about the new authentication entry point. Connected app uses standard OAuth 2.0 protocol to authenticate.

OAuth 2.0 Username-Password Flow In Salesforce

Here are the three major steps involved in Username-Password Flow in Salesforce.

1) The connected app generate an access token by sending the request to Salesforce token end point.

2) After verifying the request, Salesforce grants an access token to the connected app.

3) The connected app can use the generated access token to access the protected data.

Below example explains how to generate access token.

public string getRequestToken() {
        string reqBody = 'grant_type=password&client_id=' + cKey + '&client_secret=' + cSecret + '&username=' + uName + '&password=' + passwd;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        HttpResponse hresp = h.send(req);
        responseWrapper wResp = (responseWrapper) JSON.deserialize(hresp.getBody(), responseWrapper.class);
        system.debug('Instance url' + wResp.instance_url);
        system.debug('session id' + wResp.access_token);
        return wResp.access_token;

grant_type: The OAuth 2.0 grant type that the connected app requests. The value must be password for this flow.

client_id: The connected app’s consumer key.

client_secret The connected app’s consumer secret.

username: The username of the user that the connected app is imitating.

password: The password of the user that the connected app is imitating.

If the request is verified the response will be returned in below format.


The data can now be access using access token from the above response.

Hope you find the post on "OAuth 2.0 Username-Password Flow In Salesforce" usefull.


  1. The approach is not working for Community user. Any help will be appreciated.