Spring安全注释不适用于服务层

时间:2016-07-14 15:11:30

标签: spring spring-mvc spring-security

我正在使用Spring安全性在方法级别定义访问规则,面对的问题是Spring安全注释不能在服务层上运行。但它们在控制器层上工作正常。

以下是我的配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());

}

@Override
public void configure(WebSecurity web) throws Exception {
    web
            .ignoring()
            .antMatchers("/api/register")
            .antMatchers("/api/activate")
            .antMatchers("/api/lostpassword")
            .antMatchers("/api/resetpassword");

}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {

    @Autowired
    private MutableAclService mutableAclService;

    @Autowired
    private RoleHierarchy roleHierarchy;

    public GlobalSecurityConfiguration() {
        super();
    }

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(mutableAclService));
        expressionHandler.setRoleHierarchy(roleHierarchy);
        return expressionHandler;
    }

}

}

服务不起作用:

@Override
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Iterable<Appliance> getAll() {
    return applianceRepo.findAll();
}

控制器效果很好:

@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<PagedResources<Appliance>> getPage(@PageableDefault Pageable pageable, PagedResourcesAssembler pagedAssembler) {
    Page<Appliance> appliancePage = applianceService.getPage(pageable);
    return ResponseEntity.ok(pagedAssembler.toResource(appliancePage, applianceAssembler));
}

1 个答案:

答案 0 :(得分:0)

我意识到将@PreAuthorize放在getAll()方法上时我错了,但我正在使用getPage(pageable)方法进行测试。 Spring安全配置运行良好。抱歉给您带来不便。