Creating id_token with Java
Sample Code to generate a id_token using Java
package com.stockal.testToken;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.stream.Collectors;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
class testIdToken1 {
public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
String privateKeyStr = Files
.readAllLines(Paths.get("<PATH_TO_FILE>\<env><partner_name>privatekey.pem"))
.stream().filter(line -> !line.contains("BEGIN") && !line.contains("END"))
.collect(Collectors.joining(""));
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
Key key = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
String jws = Jwts.builder()
.claim("stockal_username","<stockal-customer-id>")
.setIssuer("<YOUR_PARTNER_CODE>")
.setAudience("stockal.com")
.setExpiration(new Date(System.currentTimeMillis() + 60000))
.signWith(SignatureAlgorithm.RS512, key)
.compact();
System.out.println(jws);
}
}
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
Updated almost 3 years ago