gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:41:15 26 4
gpt4 key购买 nike

我正在使用 Spring 安全性在方法级别定义访问规则,并且面临的问题是 Spring 安全性注释在服务层上不起作用。但它们在 Controller 层正常工作。

这是我的配置:

@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();
}

Controller 运行良好:

@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));
}

最佳答案

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

关于Spring 安全注释不适用于服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38377911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com