2015-11-04 158 views
2

這裏是我的代碼:春天@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; 
} 
} 
+0

是否有一個特定的原因,爲什麼你的控制器作爲@PreAuthorize(「denyall」)?如果preauth在該類上失敗,那麼它甚至不會嘗試嘗試preauth。 –

+0

@JeffWang我刪除了denyall,但是一旦擁有管理員角色的用戶在沒有'view_user'權限的情況下登錄,仍然可以訪問url。我相信預授權不起作用。你有什麼建議,謝謝 –

+0

據我所知,過濾器鏈首先被擊中,因此評估的第一個規則是具有Admin角色。其次是班級preauth,這是否認所有。第三種方法是通過兩種方法獲得,方法級別preauth,它具有user_view的作用。 denyall工作的事實意味着preauth正在工作。您可能希望檢查登錄用戶在listUsers方法中具有的角色。 (SecurityContextHolder.getContext()。getAuthentication()。getAuthorities()) –

回答

3

通常情況下,Spring Security在根應用程序上下文中可用,Spring MVC bean在子上下文中初始化。 因此org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor無法檢測到您的控制器bean,因爲它們存在於根環境未知的子環境中。

@EnableGlobalMethodSecurity<global-method-security>必須放置在同一配置類或XML文件在您的Spring MVC CONFIGRATION住在爲了使@PreAuthorize@PostAuthorize內。