function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yashpal YadavYashpal Yadav 

Generate access-token of Salesforce via token of Keycloak

Hello,
I would like to generate access-token of salesforce via token of Keycloak (A Third-Party open Id auth provider).
Is it possible? if yes then what steps I should follow for the same.
AnudeepAnudeep (Salesforce Developers) 
Hi Yashpal, 

To get an access token from Keyclaok , a POST method to KeyCloak end point should be used, it includes the client secret, client id, username and the granttype.

See the example code. This is taken from here
 
public static string getToken(){
    string accessToken='';
    string clientId = 'Your id';
    string clientSecret='Your secret' ;
    string username=UserInfo.getUserName();
    string payload = 'client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&grant_type=client_credentials';
    HttpRequest req = new HttpRequest();
    req.setMethod('POST');req.setEndpoint('https://yourdomain/auth/realms/yourrealm/protocol/openid-connect/token');
    req.setHeader('Content-Type','application/x-www-form-urlencoded');
    req.setHeader('Content-Length',String.valueOf(payload.length()));
    req.setBody(payload);
    Http binding = new Http();
    HttpResponse res = binding.send(req);
    if (res.getStatusCode() == 200) {
        JSONParser parser = JSON.createParser(res.getBody()); 
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() =='access_token')){
                parser.nextToken();
                accessToken= parser.getText();
            }
        }
    }
    System.debug('accessToken : ' +  accessToken);
    return accessToken;
}
Also, review the following documentation

​​​​​​http://https://help.salesforce.com/articleView?id=sso_provider_openid_connect.htm&type=0

Let me know if it helps

Anudeep