How to generate / verify ID token in Java Memo

A note on how to generate / validate an Open ID Connect / ID token in Java.

Generation method

Generation of signature information

OpenSSL is used to generate the private key and public key for signing.

** 1. Generate a private key. ** **

#Generate a private key in PEM format.
openssl genrsa -out jwt-private-key.pem 2048
#PKCS8 private key in PEM format/Convert to DER format.
openssl pkcs8 -in jwt-private-key.pem -topk8 -nocrypt -outform DER -out jwt-private-key.pk8

** 2. Generate a public key. ** **

#Generate a public key in DER format.
openssl rsa -in jwt-private-key.pem -pubout -outform DER -out jwt-public-key.der

** 3. Base64-encode the private key (jwt-private-key.pk8) and public key (jwt-public-key.der) and save them in a configuration file. ** * Implemented according to the use case.

Obtaining signature information from Base64 encoded strings

Obtain the private key as RSA PrivateKey type and the public key as RSAPublicKey type from the signature information (Base64 encoded character string) stored in the configuration file or DB.

/**
 *Get the RSA private key from the Base64 encoded string.
 */
private RSAPrivateKey getRSAPrivateKeyFromBase64String() throws NoSuchAlgorithmException,InvalidKeySpecException {
    String privateKeyAsBase64String = "Base64 format private key * Acquisition process omitted";
    byte[] privateKeyAsByteArray = Base64.decodeBase64(privateKeyAsBase64String);
    PKCS8EncodedKeySpec pkcs8ks = new PKCS8EncodedKeySpec(privateKeyAsByteArray);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = kf.generatePrivate(pkcs8ks);    
	return (RSAPrivateKey)privateKey;    
} 

...
/**
 *Get the RSA public key from the Base64 encoded string.
 */
private RSAPublicKey getRSAPublicKeyFromBase64String() throws NoSuchAlgorithmException,InvalidKeySpecException{
    String publicKeyAsBase64String = "Base64 format public key * Acquisition process omitted";
    byte[] publicKeyAsByteArray = Base64.decodeBase64(publicKeyAsBase64String);
    X509EncodedKeySpec x509ks = new X509EncodedKeySpec(publicKeyAsByteArray);   
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = kf.generatePublic(x509ks);
    return (RSAPublicKey)publicKey;    
} 
...

ID token generation

/** 
 * Base64 URL-Generate an ID token in encoded format.
 * sub:ID token issue destination subject(User ID)
 * aud:ID token issuance destination client ID
 * acr:Authentication context
 */
public String createIDToken(String sub, String aud, String acr) throws ParseException, JOSEException {
    //Payload preparation
    //Token issuer information
    String iss = "Issuer information acquired from configuration files, etc. * Acquisition processing omitted";
    //Token issuance date and time
    Date iat = new Date();
    //Token expiration date( =Issue date and time+Validity period)
    Long expiresIn = "Token validity period acquired from configuration file or DB * Acquisition process omitted";
    Date exp = new Date(iat.getTime() + expiresIn * 1000);
    IDTokenClaimSet cs = new IDTokenClaimSet(new Issuer(iss), new Subject(subject), Arrays.asList(new Audience(aud)), exp, iat);
    //Set necessary claims such as authentication context...
    cs.setACR(new ACR(acr));
    
    SignedJWT jwt = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256),cs.toJWTClaimSet());
    //signature
    jwt.sign(new RSASSASigner(getRSAPrivateKeyFromBase64String()));
    // Base64 URL-Convert to encoded format
    return jwt.serialize();
}

Method of verification

/** 
 *Perform ID token verification processing.
 */
public Boolean verifyIDToken(String idToken) throws ParseException, JOSEException {
    SignedJWT jwt = SignedJWT.parse(idToken);
    //Signature verification
    RSASSAVerifier verifier = new RSASSAVerifier(getRSAPublicKeyFromBase64String());
    if(false == jwt.verify(verifier)){
        return false;
    }
    //Payload perspective
    JWTClaimSet cs = jwt.getJWTClaimSet();
    //iss verification
    String iss = "Issuer information acquired from the configuration file or DB * Acquisition process omitted";
    if(!iss.equals(cs.getIssuer())){
        return false;
    }
    //exp verification
    if(new Date().after(cs.getExpirationTime())){
        return false;
    }
    //aud verification
    String aud = "Client ID issued to itself";
    if(!aud.equals(cs.getAudience().get(0))){
        return false;
    }
    //Verify other claims such as other acr...
    
    return true;
}

Reference information

Recommended Posts

How to generate / verify ID token in Java Memo
How to learn JAVA in 7 days
How to use classes in Java?
How to name variables in Java
How to concatenate strings in java
Memo: [Java] How to check groupId etc. described in pom.xml
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
How to do base conversion in Java
How to implement coding conventions in Java
How to embed Janus Graph in Java
How to get the date in java
How to specify id attribute in JSF
How to read log4j configuration file in Java project summarized in jar file Memo
(Memo) How to solve dummy output in Ubuntu 20.04
How to display a web page in Java
How to hide null fields in response in Java
[Java] How to substitute Model Mapper in Jackson
How to solve an Expression Problem in Java
[Java] Memo on how to write the source
How to write Java String # getBytes in Kotlin?
How to automatically generate a constructor in Eclipse
How to call functions in bulk with Java reflection
How to create a Java environment in just 3 seconds
[Java] How to omit the private constructor in Lombok
How to input / output IBM mainframe files in Java?
How to create a data URI (base64) in Java
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
How to Git manage Java EE projects in Eclipse
Summary of how to implement default arguments in Java
How to put old Java (8 series) in macOS 10.15 Catalina
[memo] Generate RSA key pair for SSH in Java
[Ruby/Rails] How to generate a password in a regular expression
Notes on how to use regular expressions in Java
[Java] Implementation method memo to set WS-Security Username Token in SOAP Stub of axis2
[Java] How to use Map
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
Java --How to make JTable
How to use java Optional
How to minimize Java images
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to use string.format
How to set Java constants
How to use Java variables
How to convert Java radix
[Java] How to implement multithreading
[Java] How to use Optional ①
How to initialize Java array
How to get the class name / method name running in Java
How to read your own YAML file (*****. Yml) in Java
How to use JSON data in WebSocket communication (Java, JavaScript)
How to store a string from ArrayList to String in Java (Personal)
What happened in "Java 8 to Java 11" and how to build an environment
How to call and use API in Java (Spring Boot)