Reputation: 105
Here is my code:
@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);
}
}
when a request /admin/* comes in, it will verify if the user has admin role by calling "antMatchers("/admin/**").hasRole("ADMIN")." , but in my controller, it does not check if the user has other permissions with @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;
}
}
Upvotes: 5
Views: 7041
Reputation: 11
try to add @EnableGlobalMethodSecurity(prePostEnabled = true)
above your Security configuration class. It is works to me!
Upvotes: 1
Reputation:
Normally, Spring Security becomes available in the root application context and Spring MVC beans are initialized in a child context.
Hence org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor
can't detect your controller beans because they live in a child context that is unknown to the root context.
@EnableGlobalMethodSecurity
or <global-method-security>
has to be placed inside the same configuration class or xml file where your Spring MVC configration lives in order to enable @PreAuthorize
and @PostAuthorize
.
Upvotes: 4