Annotation-based Role access security for Spring Boot - roles configuration on MongoDB
Working on a research project in my company, I needed a nice way to define Security Access to my services. Java Annotation is the answer. Read the story to see the code details
The system is based on a microservices architecture using spring boot as actuator. Users are registered on MongoDB in User collection with the following schema example:
I needed a way to annotate my spring Controller methods with a @Role annotation as follows:
In the previous example, I wanted to permit the access to the web method only to connected users with a “read-user” Role configured in my MongoDB.
It is composed by two annotations definition and some other configuration classes:
@EnableRoleChecking
This class is needed by the root Spring Boot Application to configure the Interception Handlers.
@Role
The @Role Annotation is needed if you want to restrict access to a method only by connected user that has the right role in the database.
The RoleConfiguration class declares the SecurityInterceptor Bean that is needed to check the roles into the DB and the RoleConfigurationProperties declares the field needed by the SecurityHandler to work properly.
You have to Add the following required properties
in Spring Boot’s application.properties or application.yml Example:
“collection” is the name of the MongoDB collection where the Users are stored.
“role-path” is the name of the property where roles are stored for the User.
“username-path” is the name of the property that corresponds to the username of the connected user.
The most important class is the SecurityInterceptor that extends the HandlerInterceptorAdapter, there are a lot of resource on the web on how this works, but essentially it declares 3 methods PreHandle, PostHandle and AfterCompletion that you can you to execute code before, after and at the end of the intercepted method. In the SecurityInterceptor I override only the PreHandle to verify the role:
The interceptor is quite straightforward, it uses the mongodb driver to find if the connected user has the annotated role into his own record.
To see how to I used it, go to the GitHub repository and read the instructions Readme