I’m implementing Spring Security in a demo Spring Boot project, I have implemented the following Spring Security Authorization for the URLs. But, I’m unable to access the GET APIs with the MANAGER and ADMIN roles. Also, when I try to access the DELETE API with the ADMIN role, I get 403 Forbidden. I’m not sure what the issue is.
@Configuration
public class DemoSecurityConfig
{
@Bean
public InMemoryUserDetailsManager userDetailsManager()
{
UserDetails john = User.builder()
.username("john")
.password("{noop}test123")
.roles("EMPLOYEE")
.build();
UserDetails mary = User.builder()
.username("mary")
.password("{noop}test123")
.roles("EMPLOYEE, MANAGER")
.build();
UserDetails susan = User.builder()
.username("susan")
.password("{noop}test123")
.roles("EMPLOYEE, MANAGER, ADMIN")
.build();
return new InMemoryUserDetailsManager(john, mary, susan);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
{
http.authorizeHttpRequests(configurer->
configurer
.requestMatchers(HttpMethod.GET, "/api/employees/").hasRole("EMPLOYEE")
.requestMatchers(HttpMethod.GET, "/api/employees/**").hasRole("EMPLOYEE")
.requestMatchers(HttpMethod.POST, "/api/employees").hasRole("MANAGER")
.requestMatchers(HttpMethod.PUT, "/api/employees/**").hasRole("MANAGER")
.requestMatchers(HttpMethod.DELETE, "/api/employees/**").hasRole("ADMIN")
);
http.httpBasic(Customizer.withDefaults());
http.csrf(csrf->csrf.disable());
return http.build();
}
}
Thanks for the help.
>Solution :
I know very little of spring security, but .roles("EMPLOYEE, MANAGER, ADMIN") why comma separated entries in a single string? looking at the docs shouldn’t that be a list like: .roles("EMPLOYEE", "MANAGER", "ADMIN")