gpt4 book ai didi

spring @PreAuthorize 不适用于 @EnableGlobalMethodSecurity(prePostEnabled = true)

转载 作者:行者123 更新时间:2023-12-03 07:43:50 26 4
gpt4 key购买 nike

这是我的代码:

@Configuration
@ComponentScan(basePackages = "com.webapp")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

@Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests().antMatchers("/resources/**").permitAll().
antMatchers("/admin/**").hasRole("ADMIN").
anyRequest().authenticated().
and().
formLogin().loginPage("/login").permitAll().
and().
logout().permitAll();
}

@Autowired
public void configureGlobal(UserDetailsService userDetailsService, AuthenticationManagerBuilder auth)
throws Exception {

auth.userDetailsService(userDetailsService);

}
}

当请求/admin/* 传入时,它将通过调用“antMatchers("/admin/**").hasRole("ADMIN") 来验证用户是否具有管理员角色。 ,但在我的 Controller 中,它不会检查用户是否具有 @PreAuthorize 的其他权限。

@Controller
@SessionAttributes({ "user" })
@RequestMapping(value = "/admin/user")
public class UserController {

static Logger logger = LoggerFactory.getLogger(UserController.class);

@Autowired
private RoleDAO roleDao;

@Autowired
private MessageSource messageSource;

@Autowired
private UserDAO userDao;

@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
@PreAuthorize("hasRole('USER_VIEW')")
public ModelAndView listUsers() {

List<User> users = userDao.list();
ModelAndView model = new ModelAndView("/admin/user/user-list");
model.addObject("users", users);
if (model.getModel().get("user") == null) {
model.getModel().put("user", new User());
}
this.loadRoles(model);
return model;
}
}

最佳答案

通常,Spring Security 在根应用程序上下文中可用,并且 Spring MVC bean 在子上下文中初始化。因此org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor无法检测到您的 Controller bean,因为它们位于根上下文未知的子上下文中。

@EnableGlobalMethodSecurity<global-method-security>必须放置在 Spring MVC 配置所在的同一个配置类或 xml 文件中才能启用 @PreAuthorize@PostAuthorize .

关于spring @PreAuthorize 不适用于 @EnableGlobalMethodSecurity(prePostEnabled = true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33530536/

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