Method-Level Security
Learn how to implement security on the method level by using some keywords.
Having put in a basic amount of security, it’s time to point out some of its issues. HTTP verb and URL rules like pathMatchers(POST, "/").hasRole(...)
grant us fine-grained control, but it has its limitations:
- Changes in the controller class could require changes in our security policy.
- As we add more controllers and, as a result, more lines to our
SecurityWebFilterChain
bean, this could get unwieldy. - What about chunks of code that need role-based security but aren’t directly linked to web endpoints?
This is where method-level security steps in.
By applying a Spring Security annotation directly on the method, we can secure things directly where our business logic is located. We can avoid having to manage security rules for the URLs of a dozen controllers and instead keep the domain of security right alongside the logic of business.
To explore method-level security, we need something a little more substantial than a couple of web methods. So for this section, we’ll add a REST API using Spring HATEOAS.
Enabling method-level security
We must opt into method-level security. It’s not activated by default. We only need to apply the following annotation (ideally to our security configuration class):
@Configuration@EnableReactiveMethodSecuritypublic class SecurityConfig {...}
Here’s a breakdown of the code above:
In line 2, this variant of SecurityConfig
shows @EnableReactiveMethodSecurity
being applied. It’s important to use the reactive version, otherwise, it won’t work properly.
Simplified security policy
The first step in moving to a method-based approach is to remove the pathMatcher()
...