Spring Boot property in @Preauthorize

后端 未结 3 1426
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 08:25

I\'m setting up a Spring Boot (v1.2.6) web project and using Spring Security (v3.2.8). I\'ve found the @PreAuthorize annotation so handy, but I don\'t know if there\'s a way

3条回答
  •  感情败类
    2021-01-14 08:42

    This maybe a generic way to evaluate expressions which i want to share with you:

    @Component("AuthorizationComponent")
    public final class AuthorizationComponent {
        private final static Logger logger = Logger.getLogger(AuthenticationUtils.class.getName());
    
        private static SpelExpressionParser parser;
        static {
            parser = new SpelExpressionParser();
        }
    
        @Autowired
        private Environment environment;
    
        public boolean evaluateExpression(final String propertyKey) {
            return checkExpression(environment.getProperty(propertyKey));
        }
    
        public static boolean checkExpression(String securityExpression) {
            logger.info("Checking security expression [" + securityExpression + "]...");
    
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
    
            Expression exp = parser.parseExpression(securityExpression);
            SecurityExpressionRoot context = new CustomMethodSecurityExpressionRoot(authentication);
            boolean result = exp.getValue(context, Boolean.class);
    
            logger.info("Check result: " + result);
    
            return result;
        }
    }
    

    And in yaml config file you can configure the path and authorization expression, something like that:

    preAuthorize:
      whatever:
        post: hasRole('MY_ROLE') OR hasAuthority('MY_AUTHORITY')
    

    Then you could use it like that over your method:

    @PreAuthorize("@AuthorizationComponent.evaluateExpression('preAuthorize.whatevert.post')")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity addQuestion(@Valid @RequestBody BodyRestDTO bodyRestDTO){
        //Code implementation
        return new ResponseEntity(HttpStatus.CREATED);
    }
    

提交回复
热议问题