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
Nikhil Khandare 1Nikhil Khandare 1 

400 Bad Request Error when calling JWT based REST Web Service

Hi All,

I am trying to call external JWT based rest webserice from salesforce. However, I am getting 400 Bad Request error. Here is the code.

    public class JWTBearerFlow 
    {     
         public static String getAccessToken(String tokenEndpoint, JWT jwt) 
         {

         String access_token = null;
         String body = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-
         type%3Ajwt-bearer&assertion=' + jwt.issue();
         HttpRequest req = new HttpRequest();  
         Blob headerValue = Blob.valueOf('username' + ':' + 'password');
         String authorizationHeader = 'BASIC ' + 
         EncodingUtil.base64Encode(headerValue);
         req.setHeader('Authorization', authorizationHeader);
         req.setMethod('POST');
         req.setEndpoint(tokenEndpoint);
         req.setHeader('Content-type', 'application/x-www-form-urlencoded');
         req.setHeader('Content-type', 'application/json');
         req.setBody(body);
         Http http = new Http();               
         HTTPResponse res = http.send(req);
         System.debug('Error Messeg:' + res.getStatus());
         if ( res.getStatusCode() == 200 ) 
         {
             System.debug('response:' + res.getStatus());
             System.JSONParser parser = System.JSON.createParser(res.getBody());
             while (parser.nextToken() != null) 
             {
                 if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                (parser.getText() == 'access_token')) 
                {
                    parser.nextToken();
                    access_token = parser.getText();
                    break;
                }
            }
         }
         return access_token;

         }
    }

         
Here is how I am giving the call to getAccessToken.

    JWT jwt = new JWT('none');
    jwt.iss = 'your issuer';
    jwt.sub = 'some subject';
    jwt.aud = 'some audience';
    JWTBearerFlow.getAccessToken('http://egrocery.flosslab.com/egrocery-
    backoffice/api/login',jwt);

Please suggest me what should bevalue of the variables
    jwt.iss
    jwt.sub
    jwt.aud

Thanks in advanced