Home

markdown notes

Authentication & Authorization

table of contents


JWT

“a JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties”

JWT, JWS, JWE, and JWK?

JOSE

JWT defines the token format and uses complementary specifications to handle signing and encryption, this collection of specifications is known as JOSE (JavaScript Object Signing & Encryption)

JWTs can be signed using a secret (with HMAC algorithm) or a public/private key pair using RSA.

Let’s explain some concepts of this definition further.

JSON Web Signature (JWS)

JSON Web Signature (JWS) claims are

A JWS is used to sign the data, making it integrity-protected:

JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());// Add the issuer,audience ,subject as per your choice
jws.setKey(privateKey);//pass the private key.
jws.setKeyIdHeaderValue(k1);
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String jwt = jws.getCompactSerialization();
System.out.println(JWT:  + jwt);

JWE (JSON Web Encryption)

JWKs (JSON Web Key Set)

import java.util.*;

import com.nimbusds.jose.jwk.*;
import com.nimbusds.jose.jwk.gen.*;

public void generateJWK() {
    // Generate 2048-bit RSA key pair in JWK format, attach some metadata
    RSAKey jwk = new RSAKeyGenerator(2048)
    .keyUse(KeyUse.SIGNATURE) // indicate the intended use of the key        
    .keyID(UUID.randomUUID().toString()) // give the key a unique ID
    .generate();

    // Output the private and public RSA JWK parameters
    System.out.println(jwk);
    
    // Output the public RSA JWK parameters only
    System.out.println(jwk.toPublicJWK());
}
import java.security.*;
import java.security.interfaces.*;
import java.util.*;

import com.nimbusds.jose.jwk.*;
import com.nimbusds.jose.jwk.gen.*;

public void generateRSAandConvertToJWK() {
    // Generate the RSA key pair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();

    // Convert to JWK format
    JWK jwk = new RSAKey.Builder((RSAPublicKey)keyPair.getPublic())
        .privateKey((RSAPrivateKey)keyPair.getPrivate())
        .keyUse(KeyUse.SIGNATURE)
        .keyID(UUID.randomUUID().toString())
        .build();
}