복붙노트

[SPRING] Spring @PreAuthorize가 @EnableGlobalMethodSecurity (prePostEnabled = true)로 작동하지 않습니다.

SPRING

Spring @PreAuthorize가 @EnableGlobalMethodSecurity (prePostEnabled = true)로 작동하지 않습니다.

여기 내 코드가 있습니다 :

@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 ")을 호출하여 사용자에게 관리 역할이 있는지 확인합니다. ,하지만 내 컨트롤러에서 사용자가 @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;
}
}

해결법

  1. ==============================

    1.일반적으로 스프링 보안은 루트 애플리케이션 컨텍스트에서 사용 가능하며 스프링 MVC 빈은 자식 컨텍스트에서 초기화된다. 따라서 org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor는 루트 컨텍스트에서 알 수없는 자식 컨텍스트에 있기 때문에 컨트롤러 빈을 감지 할 수 없습니다.

    일반적으로 스프링 보안은 루트 애플리케이션 컨텍스트에서 사용 가능하며 스프링 MVC 빈은 자식 컨텍스트에서 초기화된다. 따라서 org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor는 루트 컨텍스트에서 알 수없는 자식 컨텍스트에 있기 때문에 컨트롤러 빈을 감지 할 수 없습니다.

    @EreableGlobalMethodSecurity 또는 는 @PreAuthorize 및 @PostAuthorize를 사용하기 위해 Spring MVC 구성이있는 동일한 구성 클래스 또는 xml 파일 내에 있어야합니다.

  2. from https://stackoverflow.com/questions/33530536/spring-preauthorize-not-working-with-enableglobalmethodsecurityprepostenabled by cc-by-sa and MIT license