In the authorization Code Flow method to fetch the Salesforce access token, a two-step request process is followed. In the first request step, a request for an authorization code is made by providing the call callback page URL of your application and client ID.
let codeRequestUrl = https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=
The Salesforce client opens the valid callback URL page with the authorization code sent in the parameters, which is then further used to make a request for the Salesforce access token.
Sample c# code:
var webClient = new WebClient() { BaseAddress = uri };
var collection = new NameValueCollection();
collection.Add("code", code);
collection.Add("grant_type", "authorization_code");
collection.Add("client_id", user.CustomerKey);
collection.Add("client_secret", user.CustomerSecret);
collection.Add("redirect_uri", callbackUrl);
byte[] responseBytes = webClient.UploadValues("", "POST", collection);
string response = Encoding.UTF8.GetString(responseBytes);
string decodedResponse = HttpUtility.UrlDecode(response);
In this process, suppose we want to send some more details in the code request step, so that the details can be used at the callback page side invoked by Salesforce. This can be achieved by using the state parameter in the first request.
In the example below, an encoded json string of user details is sent, so that it can be utilized at the callback page:
const stateObj = { username:
userid:
usertype:
};
const stateParam = btoa(JSON.stringify(stateObj));
window.open(result.TokenUrl + "&state=" + stateParam, "_blank");
In the callback page, fetch the authorization code along with other parameters. The state parameter is retrieved to get the user details json, which is in encoded form and needs to be decoded as follows:
var parameters =
const encodedState = parameters["state"];
const decodedStateJson = atob(encodedState); // Base64 decode
const stateObjParsed = JSON.parse(decodedStateJson);