Search code examples
springspring-security

Using other bean and method in Spring Security @PreAuthorize


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:

A bean class:

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;
    }
}

In controller:

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

Error message:

Failed to evaluate expression 'accessBean.getPermision()'

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


Solution

  • You have to use @, see Spring Security Reference:

    Referring to Beans in Web Security Expressions

    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) {
                  ...
          }
    }
    

    You could refer to the method using:

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

    or in Java configuration

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