這裏是我的代碼:春天@PreAuthorize不@EnableGlobalMethodSecurity工作(prePostEnabled =真)
@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);
}
}
當一個請求/管理/ *進來時,它會驗證用戶通過調用具有管理員角色「 antMatchers( 「/管理/ **」)。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;
}
}
是否有一個特定的原因,爲什麼你的控制器作爲@PreAuthorize(「denyall」)?如果preauth在該類上失敗,那麼它甚至不會嘗試嘗試preauth。 –
@JeffWang我刪除了denyall,但是一旦擁有管理員角色的用戶在沒有'view_user'權限的情況下登錄,仍然可以訪問url。我相信預授權不起作用。你有什麼建議,謝謝 –
據我所知,過濾器鏈首先被擊中,因此評估的第一個規則是具有Admin角色。其次是班級preauth,這是否認所有。第三種方法是通過兩種方法獲得,方法級別preauth,它具有user_view的作用。 denyall工作的事實意味着preauth正在工作。您可能希望檢查登錄用戶在listUsers方法中具有的角色。 (SecurityContextHolder.getContext()。getAuthentication()。getAuthorities()) –