Sunday, August 23, 2020

Explain what is 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.

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.

To request an access token, the connected app sends the user’s username and password as an out-of-band POST to the Salesforce token endpoint.

grant_type=password&

client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&

client_secret=1955279925675241571&

username=testuser@salesforce.com&

password=mypassword

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();

        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.

2 comments:

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

    ReplyDelete