Issue
I'm using Spring Security in my project. I have a condition where the anonymous users should be able to read from database whereas only authorized users to add/update/delete. How can we mention such situation in the security-config?
.antMatchers("/user/**").permitAll()
permit all requires to be authenticated but I want even non-authenticated users to access via the GET method.
@RequestMapping("/user")
@PreAuthorize("hasAuthority('USER')")
public List<UserAll> getAll() {
return userService.getAll();
}
And here how do I mention that this function should be accessed by anonymous users too?
Solution
In my WebSecurityConfig class I use this:
.authorizeRequests()
.antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**")
.permitAll()
.antMatchers("/secure/rest/**")
.authenticated()
.antMatchers("/register**")
.anonymous()
.antMatchers("/login**")
.anonymous()
.and();
What this does is it ONLY allows unauthenticated users to use the register and login endpoints. It allows ONLY authenticated users to access other endpoints (ones that start with /secure/rest. It also allows my Swagger endpoints to be used by both authenticated and unauthenticated users.
permitAll does not require the user to be authenticated. It allows all requests through.
As a side note I recommend having different security configs per environment. I don't recommend exposing Swagger endpoints to everybody in prod environments. The above config is for my lower development environments.
Answered By - Clayton
Answer Checked By - Terry (JavaFixing Volunteer)