Spring Security基于角色的授权不起作用

eni9jsuy  于 11个月前  发布在  Spring
关注(0)|答案(1)|浏览(132)

我在一个演示Sping Boot 项目中实现了Spring Security,我已经为URL实现了以下Spring Security授权。但是,我无法使用MANAGERADMIN角色访问GET APIs。此外,当我尝试使用ADMIN角色访问DELETE API时,我得到了403 Forbidden。我不确定问题是什么。

@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();
    }
}

字符串
谢谢你的帮忙。

njthzxwz

njthzxwz1#

我对Spring Security 知之甚少,但是.roles("EMPLOYEE, MANAGER, ADMIN")为什么要在单个字符串中以逗号分隔条目?查看文档不应该是这样的列表:.roles("EMPLOYEE", "MANAGER", "ADMIN")

相关问题