Spring Security基于角色的授权问题

nbewdwxp  于 12个月前  发布在  Spring
关注(0)|答案(2)|浏览(228)

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

字符串

酒店DOMAINS

@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"}
}


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

vvppvyoh

vvppvyoh1#

你必须至少定义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;
}

字符串

8xiog9wr

8xiog9wr2#

使用@Secured时,无需添加前缀ROLE_只需使用此

@RestController 
public class TesController {
    @RequestMapping(value="/authController")
    @Secured("ADMIN")
    String test(){ return "I am secure for ROLE_ADMIN"}
}

字符串

相关问题