1

I'm trying to use Keycoak as identity provider for SSO.

Following salesforce help example , I managed to create the login page, redirection, and the user can login succesfulyy , however I wasn't able to obtain access token.

I tried the following inside AutocreatedRegHandler :

    string accessToken = Auth.AuthToken.getAccessToken(AuthProviderId, 'Open ID Connect');
    System.debug('accessToken :' + accessToken );

but accessToken returns null hence authentication is not successful.

I also added Auth provider's scoop but nothing changed.

How to get access_token ?

0

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

Follow the example below as well as check more info on KeyCloak's docs

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.