By Marone: December 2019
Secure Spring boot Rest APIs with client certificate
Goal
This is part III of a series of articles onSpring security
topic. In this part, we will use X.509 certificate authentication.
For creating certificates stuff, please take a look on this tutorial
Used technologies
JDK 1.8Maven 3.2 (Spring boot 2.x and Spring security 5.x)
Maven
Configuration
- In Lines between(18-25) are all urls public except
/protected
and/admin
, for the urls below we force X509 authentication:- The
/protected
url is protected by the USER role - The
/admin
url is protected by the ADMIN role
- The
- subjectPrincipalRegex is used to extract the username from the X.509 certificate
- The regular expression
CN=(.*?),
matches thecommon name
field - The extracted username will be passed to userDetailsService()
- In Lines between(28-40) we implement the UserDetailsService.loadUserByUsername interface with some dummy Users
- If the client presents a valid certificate and the extracted username matches the dummy username and their role, the user will be authenticated
Configure application.properties
- Specifing the keystore location, format
@PKCS12
and password - Specifing the truststore location, format
@JKS
and password, JKS stands for Java Keystore - Authentication via
client-certificate
is possible
The API
Project structure
Let's test
- Calling
/admin
without a certificate returns 403 status - To access
/admin
we pass theP12
file with the corresponding password and username should have the expected ROLE - According to the dummy UserDetailsService only the user john is authorized to consume
/protected
References
The complete code can be found in GitHub