我已经在我的应用程序中实现了 Spring Security。 它是基于无状态令牌的身份验证和基于用户名/密码的身份验证。
我已经配置了用户身份验证,但基于角色的授权不起作用。
具有
ROLE_USER
的用户能够访问具有 ROLE_ADMIN
的控制器方法。
这是配置。
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Bean
AuthenticationProvider passwordBasedAuthenticationProvider() {
return new PasswordBasedAuthenticationProvider();
}
@Bean
AuthenticationProvider tokenBasedAuthenticationProvider(){
return new TokenBasedAuthenticationProvider();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/v1/public/**");
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
csrf().disable().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().
authorizeRequests().
anyRequest().authenticated().
and().
anonymous().disable();
http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(passwordBasedAuthenticationProvider()).
authenticationProvider(tokenBasedAuthenticationProvider());
}
}
域名
@Entity
public class Role implements GrantedAuthority {
private long id;
private String authority;
}
public class User implements UserDetails{
private String username;
private String passwordHash;
private Role role;
}
@RestController
public class TesController {
@RequestMapping(value="/authController")
@Secured("ROLE_ADMIN")
String test(){ return "I am secure for ROLE_ADMIN"}
}
此配置有什么不正确的地方?
您必须至少使用类似这样的内容或您的情况下的任何配置来定义 RoleHierarchie:
@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl r = new RoleHierarchyImpl();
r.setHierarchy("ROLE_ADMIN > ROLE_STAFF");
r.setHierarchy("ROLE_STAFF > ROLE_USER");
r.setHierarchy("ROLE_DEVELOPER > ROLE_USER");
r.setHierarchy("ROLE_USER > ROLE_GUEST");
return r;
}
当你使用@Secured时,不需要添加前缀ROLE_只需使用这个
@RestController
public class TesController {
@RequestMapping(value="/authController")
@Secured("ADMIN")
String test(){ return "I am secure for ROLE_ADMIN"}
}