I am building a two service app in Java Spring Boot where one service is an auth service that generates a jwt and the other one is a resource service, that decodes the jwt and returns list of posts based on the jwt subject.
My current auth service setup has a .jks key pair stored in the resources and a login endpoint that:
- checks that the username exists in MongoDB and that the password matches the stored encoded one
- if the check passes, returns a jwt with the username in subject
My resource server has a method that decodes the jwt at the preHandle() stage and looks like this:
@Value("${jwt.key}")
private String publicKey;
public Claims decodeJWT(String jwt) {
KeyFactory kf;
PublicKey key;
publicKey = publicKey
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace("\n", "")
.trim();
try{
kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubKeySpecX509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
key = kf.generatePublic(pubKeySpecX509EncodedKeySpec);
} catch (Exception e) {
throw new RuntimeException("Failed to generate Public Key", e);
}
//This line will throw an exception if it is not a signed JWS (as expected)
return Jwts.parser()
.requireIssuer("auth-service")
.requireAudience("posts-service")
.setSigningKey(key)
.parseClaimsJws(jwt).getBody();
}
My only issue with this is that I need to manually export the public key from the auth service .jks file and store it in the resource service application.yml file.
My question therefore is: What would be the best way to create a jwks endpoint in the auth service, that returns the public key from the .jks file? and how to best add a call to it from the resource service?
Cheers Kris