有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用HttpSecurity(Spring Security)应用角色?

我使用的是Spring Security 3.2.3。释放

下面是我的Web安全配置适配器的代码

@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是否有两个授权机构,名称为:ADMIN,USER

那么,你知道是什么导致了这个问题吗


共 (2) 个答案

  1. # 1 楼答案

    回答我自己的问题

    显然,Spring Security会自动在每个角色名中添加前缀ROLE_uu。因此,在我的数据库中的每个角色名称中添加角色前缀就解决了这个问题

  2. # 2 楼答案

    从方法hasRole(String role)的javadoc:

    Shortcut for specifying URLs require a particular role. If you do not want to have "ROLE_" automatically inserted see hasAuthority(String).

    所以你可以用hasAuthorityhasAnyAuthority代替