Issue
My security config class (which inherits from WebSecurityConfigurerAdapter
) has a method like the following.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/restaurant/**").access("hasRole('ROLE_USER')")
.and()
.formLogin();
}
However I'd rather use @PreAuthorize
on my controllers instead. If I remove the method everything requires auth. What should my method look like so everything is available and access is only determined by PreAuthorize?
Solution
As has been already stated, it is not very common to use method level security to secure controller methods but rather to secure methods with business logic. And even if you need to perform authorization based on request attributes, it should be possible to achieve this with URL based security and web security expressions.
Available expressions are defined by
WebSecurityExpressionRoot
class, an instance of which is used as the expression root object when evaluation web-access expressions. This object also directly exposed theHttpServletRequest
object under the namerequest
so you can invoke the request directly in an expression.
Here you can find more details on when to use URL based security and when method level security.
Answered By - pgiecek
Answer Checked By - Willingham (JavaFixing Volunteer)