【问题标题】:Spring Security role-based authorisation issueSpring Security 基于角色的授权问题
【发布时间】:2016-07-01 21:11:23
【问题描述】:

我已经在我的应用程序中实现了 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"}
}

这个配置有什么不正确的地方?

【问题讨论】:

  • 您的配置中实际上没有提到ROLE_USERROLE_ADMIN。我只习惯使用 XML 配置。应该在哪里定义角色,以便TesController 可以实际接他们?
  • 如果你改变你的configure方法,加上.antMatchers("/authController").access("hasRole('ADMIN')"),情况是一样的吗?

标签: java spring spring-security authorization


【解决方案1】:

您必须至少定义 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;
}
猜你喜欢
  • 2020-06-16
  • 2020-07-09
  • 2020-09-13
  • 2021-02-15
  • 2017-10-19
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多