How to use JWT with Salesforce API?

Jimmy Hua
Jimmy Hua
Jan 1, 2018 · 4 min read

How to generate certificate, key and keystore?


Upload Certs to Salesforce


Libraries need to include in your java project


Code the JWT Generation

public static String generateJwt() {
try {
String jksKeyStoreFilePath = ""; // Path to the *.jks file
String keyStorePassword = ""; // The password that the keystore
// is locked with
KeyStore keystore = KeyStore.getInstance("JKS")
keystore.load(new FileInputStream(jksKeyStoreFilePath),
keyStorePassword.toCharArray());
PrivateKey privateKey = (PrivateKey)
keystore.getKey(keyStoreAlias,
keyStorePassword.toCharArray());
String iss = ""; // consumer ID from Salesforce
String sub = ""; // username that you are logging in as
String aud = ""; // https://test.salesforce.com or
// https://login.salesforce.com
String jwt = Jwts.builder() //
.setIssuer(iss) // identifies principal that issued the JWT
.setSubject(sub) // identifies the subject of the JWT
.setExpiration(exp) // identifies the expiration time on or
// after which the JWT must not be
// accepted for processing
.setAudience(aud) // identifies the recipients that the
// JWT is intended for
.signWith(SignatureAlgorithm.RS256, privateKey) //
.compact();
return jwt;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

Code the Salesforce API call with JWT to get Access Token

private static String generateAccessToken(String jwt) {  String tokenEndpoint = ""; // https://test.salesforce.com or 
// https://login.salesforce.com
String consumerID = ""; // From Salesforce
String consumerSecret = ""; // From Salesforce
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(tokenEndpoint);
post.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
post.addParameter("assertion", jwt);
post.addParameter("client_id", consumerId);
post.addParameter("client_secret", consumerSecret);
post.addParameter("redirect_uri", "https://localhost:1717/OauthRedirect");
String responseBody = null;
try {
httpclient.executeMethod(post);
responseBody = post.getResponseBodyAsString();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String accessToken = null;
JSONObject json = null;
try {
json = new JSONObject(responseBody);
Map<String, Object> map = json.toMap();
if (map.containsKey("error")) {
System.out.println(map.get("error"));
System.out.println(map.get("error_description"));
} else {
accessToken = json.getString("access_token");
return accessToken;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static SoapConnection createSoapConnection(String accessToken) throws ConnectionException {ConnectorConfig config = new ConnectorConfig();
config.setSessionId(accessToken);
config.setServiceEndpoint(“https://login.salesforce.com/services/Soap/c/41.0");
return config;

return new SoapConnection(config);
}

Understanding the different endpoints


Maven Snippet

<dependencies>
<dependency>
<groupId>com.force.api</groupId>
<artifactId>force-wsc</artifactId>
<version>42.0.0</version>
</dependency>
<dependency>
<groupId>com.force.api</groupId>
<artifactId>force-partner-api</artifactId>
<version>42.0.0</version>
</dependency>
<dependency>
<groupId>com.force.api</groupId>
<artifactId>force-metadata-api</artifactId>
<version>42.0.0</version>
</dependency>
<dependency>
<groupId>com.force.api</groupId>
<artifactId>force-apex-api</artifactId>
<version>42.0.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.58</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

Jimmy Hua

Written by

Jimmy Hua

I do many things. I am an engineer, entrepreneur, philanthropist, and just someone who wants to see the world becoming a better place for all.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade