微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Spring安全性和spring安全对象的属性限制对URL的访问?

我正在使用Spring 5.1和Spring security 4.2.我使用XML文件配置了访问规则.我的问题是,如何根据Spring安全上下文中的属性编写拦截规则(对URL的访问控制)?也就是说,我有一个变量

productList

在安全上下文中,类型为java.util.ArrayList.如果此列表为空或null,我想限制对URL的访问.我怎么写这个?我有

ecurity" security-context-repository-ref="myContextRepository"
    auto-config="false" use-expressions="true" authentication-manager-ref="authenticationManager"
    entry-point-ref="loginUrlAuthenticationEntryPoint">
    ...
    

但当然,上面

length(principal.productList) > 0   

表达是完全错误的.有没有正确的方法来写它?

最佳答案
与安全相关的表达式在Spring中具有非常有限的操作集.您可以通过提供org.springframework.security.access.expression.SecurityExpressionoperations接口的自定义实现来扩展此集.以下是如何操作的简要指南:

>在SecurityExpressionoperations上创建包装器并实现所需的操作:

class MySecurityExpressionoperations implements SecurityExpressionoperations {
    private SecurityExpressionoperations delegate;

    public MySecurityExpressionoperations(SecurityExpressionoperations delegate) {
        this.delegate = delegate;
    }

    public boolean hasProducts() {
        MyUser user = (MyUser) delegate.getAuthentication().getPrincipal();
        return !user.getProductList().isEmpty();
    }

    // Other methods
}

>扩展org.springframework.security.web.access.expression.WebExpressionVoter并替换标准表达式处理程序:

class MyWebExpressionVoter extends WebExpressionVoter {
    public MyWebExpressionVoter() {
        setExpressionHandler(new DefaultWebSecurityExpressionHandler() {
            @Override
            protected SecurityExpressionoperations createSecurityExpressionRoot(Authentication authentication,FilterInvocation fi) {
                SecurityExpressionoperations delegate = super.createSecurityExpressionRoot(authentication,fi);
                return new MySecurityExpressionoperations(delegate);
            }
        });
    }
 }

>提供自定义访问决策管理器:

ecurity.access.Vote.AffirmativeBased">
    Voter"/>
        

>应用自定义访问决策管理器:

>使用其他安全操作保护其中一个URL:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐