2
我正在使用Spring安全性來定義方法級別的訪問規則,並且面臨的問題是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));
}
您需要在WebSecurityConfig或其他地方添加@EnableGlobalMethodSecurity註釋。 – Zemzela
@Zemzela我添加了@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true),但是不起作用。 –
請閱讀:http://websystique.com/spring-security/spring-security-4-method-security-using-preauthorize-postauthorize-secured-el它應該是有幫助的 – Zemzela