How to use custom expressions in Spring Security @PreAuthorize/@PostAuthorize annotations

后端 未结 3 1097
名媛妹妹
名媛妹妹 2020-12-02 07:05

Is there a way to create more expressive statements in @Preauthorize blocks? Here\'s an example of something I find myself repeating, because the @Preauthorize is not terrib

3条回答
  •  猫巷女王i
    2020-12-02 08:03

    You could write your annotation something like:

    @PreAuthorize("hasRole('ROLE_ADMIN') and hasPermission(#id, 'Game', 'DELETE')")
    

    To get the hasPermission part working you need to implement PermissionEvaluator interface.

    Then define an expression handler bean:

    @Autowired
    private PermissionEvaluator permissionEvaluator;
    
    @Bean
    public DefaultMethodSecurityExpressionHandler expressionHandler()
    {
        DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
        handler.setPermissionEvaluator(permissionEvaluator);
        return handler;
    }
    

    And inject in your security config:

    
      
    
    

提交回复
热议问题