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.

WHAT IS CONNECTED APP IN SALESFORCE?

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) Using 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 if we are calling another Salesforce system to get token from Salesforce system.



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();
        req.setBody(reqBody);
        req.setMethod('POST');
        req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
        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.


{"id":"https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P",
"issued_at":"SomeTimeStamp",
"instance_url":"https://yourInstance.salesforce.com/",
"signature":"",
"access_token":"",
"token_type":"Bearer"}

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.

No comments:

Post a Comment