OAuth 2.0 Authorization Code Grant Type Using Salesforce

|
| By Webner

As I mentioned in my previous post what is Oauth 2.0 authorization code grant type.

To implement this authorization in Salesforce we have to perform the following steps”

  • Implement apex code to send first request
    String client_id = '*******************';
    String client_Secret = '************';
    Blob headerValue = Blob.valueOf(client_id + ':' + client_Secret);
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('*********');
    req.setMethod('POST');
    String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
    req.setHeader('Authorization',authorizationHeader);
    req.setHeader('Content-Type','application/x-www-form-urlencoded');
    String callBackCode = ‘**************’;
    req.setHeader('Accept','application/json');
    req.setBody('grant_type=authorization_code&code=' + callBackCode + '&redirect_uri=*****');
  • This code sends a request to the API server. It will be processed and redirected to the URL present in the query string ‘redirect_uri’.
  • This Uri contains an access token and related details. To achieve this in salesforce we need to create sites.
  • Sites use the Visual force page which will be opened when the URL got hit. On that VF page, we access the access token.
  • Now we can store it and use it anywhere we need and refresh the token anytime whenever we need

Leave a Reply

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