Spring 引导/Spring 基于安全角色的授权无法正常工作

Spring Boot / Spring Security role based authorization not working properly

我正在尝试通过 Spring Boot 学习 Spring 安全性。我有一个正在实施它的演示。它适用于登录页面和配置文件方法,可以由任何有效用户进行身份验证。但是当我尝试访问特定角色时它不起作用并给我一个“403 - 访问被拒绝”。

我的接入点>>

    @Controller
public class HomeController {

    @RequestMapping("/")
    public String home() {
        return "/home.jsp";
    }

    @RequestMapping("/profile")
    public String profile() {
        return "/profile.jsp";
    }

    @RequestMapping("/admin")
    public String admin() {
        return "/admin.jsp";
    }

    @RequestMapping("/management")
    public String management() {
        return "/management.jsp";
    }

}

我的配置方法>>

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/login", "/").permitAll()
            .antMatchers("/profile").authenticated()
            .antMatchers("/admin").hasRole("ADMIN")
            .antMatchers("/management").hasAnyRole("ADMIN", "MANAGEMENT")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll()
            .and()
            .logout().invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/logout-success").permitAll();
}

我的角色分配 >>

    @Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return Collections.singleton(new SimpleGrantedAuthority("ADMIN"));
}

我认为这是 Spring 安全性最不明显的地方。角色和权限是一回事,但角色应该以 ROLE_ 为前缀。所以,正确的用法是

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"));
}