I'm trying to implement different roles in my application and I cannot achieve to include/exclude URLs for different roles.
For example, I want that users with role ROLE_USER and anonymous users can access to the following endpoints:
String[] publiclyAccessibleUris = new String[]{ "/home", "/user", "/profile/*", "location/**", "/products/*" };
And I want that users with role ROLE_DENIED can only access to the following endpoints:
String[] publiclyAccessibleUrisForDenied = new String[]{ "/home", "/profile/*" };
Here is my code:
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.anonymous()
.and()
.authorizeRequests()
.antMatchers(publiclyAccessibleUris).hasRole("USER")
.anyRequest().permitAll()
.antMatchers(publiclyAccessibleUrisForDenied).hasRole("DENIED")
.anyRequest().permitAll()
.antMatchers("/**").hasRole("DENIED")
.anyRequest().denyAll();
How can I achieve this?
Finally i solved like the following way in order to allow all urls for all users with anon o ROLE_USER, and for ROLE_SUSPENDED i set wich one i want to.
http
.sessionManagement().sessionCreationPolicy(STATELESS)
.and()
.anonymous()
.and()
.authorizeRequests()
.antMatchers(publiclyAccessibleUris).permitAll()
.antMatchers(publiclyAccessibleUrisForDenied).access("hasRole('ROLE_DENIED') or hasAuthority('DENIED') OR hasRole('ROLE_USER') or hasAuthority('USER')")
.anyRequest().access("hasRole('ROLE_USER') or hasAuthority('USER')");