Last updated: 2024-07-25
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.
We start by using the following commands to 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.
Commands to generate our key pair
The conversion of our keys into the classes RSAPublicKey
and RSAPrivateKey
is done automatically by Spring Boot. The used library com.auth0:java-jwt
already provides all required functions for switching the algorithm.
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.
See Pricing
or read quickstart