【问题标题】:Using other bean and method in Spring Security @PreAuthorize在 Spring Security @PreAuthorize 中使用其他 bean 和方法
【发布时间】:2017-07-29 02:58:56
【问题描述】:

我想在 Spring Security 中将 @PreAuthorize 与 SpEL 一起使用,例如 http://forum.spring.io/forum/spring-projects/security/100708-spel-and-spring-security-3-accessing-bean-reference-in-preauthorize 中的示例 但这对我在 Spring Security 4.1.4 中使用时不起作用。以下是我的示例代码:

一个 bean 类:

package com.service.spel;

import org.springframework.stereotype.Component;

@Component(value="accessBean")
public class AccessCheckBean {
    public String getPermision(){
        /**
         * return the api permision
         */
        String scope = "#oauth2.hasScope('resource.Update')";
        return scope;
    }
}

在控制器中:

    @PreAuthorize("accessBean.getPermision()")
    @GetMapping("/perm")
    public @ResponseBody String getPerm(){
        return "Perm";
    }

错误信息:

无法评估表达式“accessBean.getPermision()”

好像我不能像上面那样使用SpEL,那么如果我使用这个版本的Spring Security,我该如何继续?

【问题讨论】:

    标签: spring-security


    【解决方案1】:

    你必须使用@,见Spring Security Reference

    在网络安全表达式中引用 Beans

    如果您希望扩展可用的表达式,您可以轻松引用您公开的任何 Spring Bean。例如,假设您有一个名为 webSecurity 的 Bean,其中包含以下方法签名:

    public class WebSecurity {
          public boolean check(Authentication authentication, HttpServletRequest request) {
                  ...
          }
    }
    

    您可以参考以下方法:

    <http>
      <intercept-url pattern="/user/**"
          access="@webSecurity.check(authentication,request)"/>
      ...
    </http>
    

    或在 Java 配置中

    http
          .authorizeRequests()
                  .antMatchers("/user/**").access("@webSecurity.check(authentication,request)")
                  ...
    

    【讨论】:

    • 所以 OP 的控制器方法中的 SpEL 将是相同的:@webSecurity.check(authentication, request) ?
    • @hc_dev:应该是@PreAuthorize("@accessBean.getPermision()")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2015-07-30
    • 2014-08-03
    相关资源
    最近更新 更多