【问题标题】:How do hasRole() and hasPermission() web security expressions work?hasRole() 和 hasPermission() Web 安全表达式如何工作?
【发布时间】:2017-10-15 06:43:48
【问题描述】:

这实际上是两个问题,因为 Spring Security 参考中没有很好地解释它。第一个问题是,在我的配置中,我有这样的代码:

 @Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/admin").access("hasRole('ADMIN')");

那么在这两种情况下,Spring 在哪里寻找当前用户的角色呢?是否可能在 UserDetailsS​​ervice 上调用 loadUserByUsername() 方法,然后在获取的 UserDetails 上调用 getAuthorities()?

我的第二个问题是关于 hasPermission() 表达式。假设我有一个自定义的 PermissionEvaluator,有没有办法让它在配置类中工作,例如:

 @Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
                .antMatchers("/admin").access("hasPermission(...)")

或者这是一个只在方法级别起作用的表达式?

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    回答您的第二个问题:是的,您可以将自己的 PermissionEvaluator 与 HttpSecurity 一起使用。首先,你必须定义一个 WebSecurityExpressionHandler 像

    final DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();           
    webSecurityExpressionHandler.setPermissionEvaluator(myPermissionEvaluator);
    

    或者像豆子一样:

    @Bean
    public DefaultWebSecurityExpressionHandler webExpressionHandler(PermissionEvaluator myPermissionEvaluator) {
        final DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
        webSecurityExpressionHandler.setPermissionEvaluator(siraPermissionEvaluator);
        return webSecurityExpressionHandler;
    }
    
    /*this option then needs to autowire the bean*/
    

    然后将它与 HttpSecurity 一起使用,例如:

    http.authorizeRequests().expressionHandler(webSecurityExpressionHandler)
    .antMatchers("/admin").access("hasPermission(...)");
    

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2018-11-23
      • 2015-06-06
      • 2020-06-26
      • 2017-10-07
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多