【问题标题】:How to apply roles using HttpSecurity (Spring Security)?如何使用 HttpSecurity (Spring Security) 应用角色?
【发布时间】:2014-05-09 10:10:33
【问题描述】:

我正在使用 Spring Security 3.2.3.RELEASE

这是我的 WebSecurityConfigurerAdapter 的代码

@Configuration
@EnableWebSecurity
public class WebSecurityContext extends WebSecurityConfigurerAdapter {

private static final Logger log = LogManager.getLogger(WebSecurityContext.class);

@Autowired
private AuthenticationProvider authenticationProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    log.info("Setting AuthenticationManagerBuilder");
    auth.authenticationProvider(authenticationProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    log.info("Configuring HttpSecurity");
    http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .httpBasic();

}
}

结果是:HTTP 状态 403 - 访问被拒绝

但如果我评论这一行:

//.antMatchers("/**").hasRole("USER")

一切正常。这意味着(我猜)我的角色或 HttpSecurity 有问题。

于是我开始调试。我仔细检查了我的 UserDetails 是否有两个 GrantedAuthorities,名称分别为:ADMIN、USER。

那么有什么想法可能导致问题吗?

【问题讨论】:

    标签: java spring configuration spring-security


    【解决方案1】:

    来自方法hasRole(String role)的javadoc:

    指定 URL 的快捷方式需要特定的角色。如果你不 想要自动插入“ROLE_”,请参阅hasAuthority(String)

    所以你可以改用hasAuthorityhasAnyAuthority

    【讨论】:

    • 那就更好了。现在我不必更改我的数据库条目。谢谢
    【解决方案2】:

    回答我自己的问题

    显然 Spring Security 会自动为每个角色名称添加前缀 ROLE_。所以在我的数据库中为每个角色名称添加 ROLE_ 前缀解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 2017-10-18
      • 2016-08-08
      • 2021-06-29
      • 2018-06-02
      • 1970-01-01
      • 2011-06-17
      • 2012-08-16
      • 1970-01-01
      相关资源
      最近更新 更多