Spring Security (series) - Authorities and Roles #6
Now that we know who you are, let's see what you CAN do 🧐 !
So we got through with the Authentication flow where we identify the user and we saw that there are more than a few ways to do that (database, third-party) . We move into the Authorization part of Security.
Authorization is the process where we check the permissions of a user to do certain actions.
Spring Security provides us two main concepts by which we define permissions:
Authority- action-based permissions (ex:
Role- role-based permissions (ex:
Practically, there is no conceptual difference between them. A role is only an authority prefixed with 'ROLE_'
Continuing on the footsteps of the database login example, let's create two endpoints that we will secure by only letting some users access them:
/admin- can only be access by users with
/client- can only be access by users with
And for the security configuration, we only need to override the
configure(HttpSecurity http) of the
WebSecurityConfigurerAdapter and use the
mvcMatchers to match URLs with roles.
Actually defining the roles for some users will require us creating 2 new tables:
role- where we define the roles in our application
user_x_role- where we match roles with users.
We need to define the
Role entity matching the
And then, the roles need to be added to the
(I know that
fetch = FetchType.EAGER is not the best thing to do in terms of performance, but for this example, it will do the trick)
The last link in the chain is to add the roles to the Spring Security
UserDetails object that gets added in the Security Context on a successful authentication.
Testing it with Postman:
As always, you can find the full code here: https://github.com/andreiszu/spring-security/tree/authorities-roles
Stay tuned! 🚀