在 Spring Security @PreAuthorize 中使用其他 bean 和方法 [英] Using other bean and method in Spring Security @PreAuthorize

查看:45
本文介绍了在 Spring Security @PreAuthorize 中使用其他 bean 和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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 中使用它时这对我不起作用.下面是我的示例代码:

I want to using @PreAuthorize with SpEL within Spring Security like the example at http://forum.spring.io/forum/spring-projects/security/100708-spel-and-spring-security-3-accessing-bean-reference-in-preauthorize but this is not work for me while using it in Spring Security 4.1.4. Below is my sample code:

一个 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()"

Failed to evaluate expression 'accessBean.getPermision()'

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

seems I can't use SpEL like above, then if I am using this version of Spring Security, how can I proceed?

推荐答案

必须使用@,见Spring 安全参考:

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

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

If you wish to extend the expressions that are available, you can easily refer to any Spring Bean you expose. For example, assuming you have a Bean with the name of webSecurity that contains the following method signature:

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

您可以参考以下方法:

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

或在 Java 配置中

or in Java configuration

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

这篇关于在 Spring Security @PreAuthorize 中使用其他 bean 和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆