JWT Token Exchange setup in Named Credentials for outbound callout

Trying to integrate with okta api from Salesforce that supports JWT Token exchange. I was able to successfully get the access token with the below code but I am blocked on how to use named credentials for JWT Token Exchange protocol to get access token.
Working code

HTTPResponse res;        
HttpRequest req = new HttpRequest();
req.setHeader('Accept', 'application/json');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setEndpoint('https://dev-05838179.okta.com/oauth2/v1/token');
req.setMethod('POST');
    String encodingHeader = base64URLencode(Blob.valueOf('{"alg":"RS256","typ":"JWT"}'));
String encodingPayload = base64URLencode(Blob.valueOf('{"sub":"0oab8vkv7bYJ2LbrH5d6","aud":"https://dev-05838179.okta.com/oauth2/v1/token","iss":"0oab8vkv7bYJ2LbrH5d6","exp":1615484889}'));
string jwt = encodingHeader +'.'+encodingPayload;
Blob signature = Crypto.signWithCertificate('rsa-sha256', Blob.valueOf(jwt), 'okta_cert');
jwt = jwt + '.'+base64URLencode(signature);        
req.setBody('grant_type=client_credentials&scope=okta.users.read&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion='+jwt);
Http http = new Http();
system.debug('req body = '+req.getBody());
res = http.send(req);
system.debug('response = '+ res.getBody());

below is my named credentials setup.

Named Credentials

Below is the code to get access token using named credentials.

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:OKTA_Token');
req.setMethod('POST');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

Thanks in advance.

Answer

Attribution
Source : Link , Question Author : sfdcdev , Answer Author : Community

Leave a Comment