如何根据自定义条件访问或授予

时间:2018-03-10 18:27:28

标签: spring

假设我想根据某些不基于角色或权限或任何事情的条件授予用户。

假设用户点击了url / getAllOrders。如果满足某些条件,我需要提供访问权。

在那种情况下,我不知道该怎么做。我检查并遇到了AccessDecisionVoter并且不确定它是否适合它并且也不知道如何实现它。

  1. 有人可以建议AccessDecisionVoter是正确的选择吗?
  2. 正在寻找使用AccessDecisionVoter
  3. 的工作示例代码段

    感谢。

1 个答案:

答案 0 :(得分:0)

在您的控制器中,您可以在处理程序方法上使用@PreAuthorize并调用在SecurityExpressionRoot的子类中声明的方法。您需要进行一些配置才能在SecurityExpressionRoot

内注册GlobalMethodSecurityConfiguration

在您的控制器中:

@PreAuthorize("isMyCustomConditionMet()")
@GetMapping("/getAllOrders")
public String allOrders(Model model) {
     model.addAttribute("orders", orderService.getAllOrders());
     return "orders";
}

在配置类中:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class CustomMethodSecurityConfig extends 
GlobalMethodSecurityConfiguration {

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new CustomMethodSecurityExpressionHandler();
    }


}

这是我们上面实例化的类:

public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {

    @Override
    protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation methodInvocation) {

        CustomSecurityExpressionRoot root = new CustomSecurityExpressionRoot(authentication);
        root.setThis(methodInvocation.getThis());
        root.setPermissionEvaluator(getPermissionEvaluator());
        root.setTrustResolver(new AuthenticationTrustResolverImpl());
        root.setRoleHierarchy(getRoleHierarchy());
        root.setDefaultRolePrefix("ROLE_");
        return root;

    }

}

这是您定义客户逻辑的地方:

public class CustomSecurityExpressionRoot extends SecurityExpressionRoot 
    implements MethodSecurityExpressionOperations {

    private Object filterObject;
    private Object returnObject;
    private Object target;

    public CustomSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    public boolean isMyCustomConditionMet() {
        return [INSERT YOUR LOGIC HERE!];
    }

    @Override
    public void setFilterObject(Object filterObject) {
        this.filterObject = filterObject;
    }

    @Override
    public Object getFilterObject() {
        return filterObject;
    }

    @Override
    public void setReturnObject(Object returnObject) {
        this.returnObject = returnObject;
    }

    @Override
    public Object getReturnObject() {
         return returnObject;
    }

    void setThis(Object target) {
        this.target = target;
    }

    @Override
    public Object getThis() {
        return target;
    }
}