我正在使用 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。
那么有什么想法可能导致这个问题吗?
最佳答案
来自方法 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)
.
因此您可以使用 hasAuthority
或 hasAnyAuthority
代替
关于java - 如何使用HttpSecurity(Spring Security)应用角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738397/