Spring Boot/Spring Security基于角色的授权无法正常工作



我正在尝试使用Spring Boot学习Spring Security。我有一个实现它的演示。它可以很好地与登录页面和配置文件方法配合使用,任何有效用户都可以对其进行身份验证。但当我试图访问某个特定角色时,它不起作用,并给我一个";403-拒绝访问";。

我的接入点>gt;

@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";
}
}

我的配置方法>gt;

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

我分配的角色>gt;

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

我认为这是Spring Security最不明显的地方。角色和权限是相同的,但角色应该以ROLE_为前缀。因此,正确的用法是

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

最新更新