Using the new Spring-Security-Web starting with 6.0.0, I wanted to know how to validate a Bearer JWT using a RS256 public key and set the "Authentication" in the Spring Security Servlet Context.
Currently I've written a custom JwtTokenFilter
which is added to a SecurityFilterChain
. It reads the public key using the X509EncodedKeySpec
jwtPublicKey
points to the .pub file
Resource resource = new ClassPathResource(jwtPublicKey);
FileInputStream is = new FileInputStream(resource.getFile());
byte[] bytes = is.readAllBytes();
is.close();
String temp = new String(bytes);
String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replace("\n", "");
// Decode the contents of the file from Base64
base64EncodedKeyBytes = java.util.Base64.getDecoder().decode(publicKeyPEM);
// Convert the contents of the file to a RSAPublicKey object
X509EncodedKeySpec spec = new X509EncodedKeySpec(base64EncodedKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
publicKey = (RSAPublicKey) kf.generatePublic(spec);
*base64EncodedKeyBytes
and publicKey
are static variables.
How can I now validate a JWT using this public key? I feel like this is all very tedious and I have the feeling there must be a shorter way already included into Spring? (oh lord, please!)