Signing JWTs with a private key in Spring Security
In the previous article, we already set up a Spring Boot application to protect our REST API using JWT. In doing so, we used the symmetric algorithm HMAC512
. How can we sign our tokens using a private key and RSA256
?
HMAC512
is a modern encryption method where the same key is used for signing and validating our tokens. This means that other applications need our secret to check the validity of the JWTs and thus can use it to issue new tokens. By switching to the asymmetric algorithm RSA256
we use a private key to sign our tokens. We can pass over the public key for validation to other partys, and they cannot issue new tokens by themselves.
With the following commands we can create our own keys. The new files public.pem
as well as private.pem
we put afterwards in resources/certs
of our Spring Boot application.
# create key pair
openssl genrsa -out keypair.pem 2048
# extract public key
openssl rsa -in keypair.pem -pubout -out public.pem
# extract private key
openssl pkcs8 -in keypair.pem -topk8 -nocrypt -inform PEM -outform PEM -out private.pem
▴ Commands to generate our key pair
The conversion of our keys into the required classes is done automatically by Spring Boot by configuring our constructor accordingly. The used library com.auth0:java-jwt
already brings all required functions for switching the algorithm.
public class JwtTokenService {
private final Algorithm rsa256;
private final JWTVerifier verifier;
public JwtTokenService(@Value("classpath:certs/public.pem") final RSAPublicKey publicKey,
@Value("classpath:certs/private.pem") final RSAPrivateKey privateKey) {
this.rsa256 = Algorithm.RSA256(publicKey, privateKey);
this.verifier = JWT.require(this.rsa256).build();
}
// ...
}
▴ Customization of our JwtTokenService class to use our keys
Our JWT can now already be signed with new algorithm by calling .sign(this.rsa256)
. No further customization is required and our Spring Boot application from the first article now uses our private key for signing our token.
In the Bootify Builder modern Spring Boot applications can be created with their own database schema. In the Professionel plan, Spring Security with JWT is available and you can choose between a symmetric and asymmetric algorithm.