【发布时间】:2016-02-05 11:02:21
【问题描述】:
这是我的代码:
@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;
}
}
【问题讨论】:
-
您的控制器作为@PreAuthorize("denyall") 是否有特殊原因?如果类的 preauth 失败,它甚至不会命中尝试 preauth 的方法。
-
@JeffWang 我删除了denyall,但是一旦具有管理员角色的用户在没有'view_user'权限的情况下登录仍然可以访问url。我确定预授权不起作用。有什么建议吗,谢谢
-
据我了解,过滤器链首先受到打击,因此评估的第一个规则是具有管理员角色。第二个是类级别的preauth,即deny all。第三个,如果两者都通过的话,是方法级别的preauth,它的角色是user_view。 denyall 正在工作的事实意味着 preauth 正在工作。您可能希望在 listUsers 方法中检查登录用户的角色。 (SecurityContextHolder.getContext().getAuthentication().getAuthorities())
-
@JeffWang denyall 从来没有工作过。这就是为什么我说预授权从未起作用。
-
hmm,看看docs.spring.io/spring-security/site/docs/3.2.x/reference/… 虽然它是针对 3.2.x,据我所知,这个特定的常见问题解答仍然适用于 4.0.x
标签: spring spring-mvc spring-security