Spring Security基于角色的授权问题

时间:2016-03-16 06:15:28

标签: java spring spring-security authorization

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

此配置有什么不正确之处?

1 个答案:

答案 0 :(得分:0)

你必须至少定义RoleHierarchie这样的东西,或者你的情况下配置可能是什么样的:

value="#{javascript:compositeData.menutItemGroup}">