小编典典

Spring safety:拦截URL模式access =“#id == 1

spring-mvc

我有项目是IAM Spring Security 3.1.3和MVC 3.2

我也想允许路径中的userid中的URL与主体userid匹配

    <security:intercept-url pattern="/user/{id}/edit" access="#id == principal.userId"/>

http use-expressions将其设置为true,并且当尝试principal.userId ==
1时,它可以工作,但是我需要使用从URL中提取的值。

我已经尝试了所有可能的组合。


阅读 395

收藏
2020-06-01

共1个答案

小编典典

这是不可能的。但是还有另一种方式。您可以定义自己的网络表达式,该表达式将负责从URL中提取id参数。可能看起来像这样:

<security:intercept-url pattern="/user/{id}/edit" access="getIdUrlPathParameter() == principal.userId"/>

为此,您需要:
1.添加扩展 WebSecurityExpressionRoot的 CustomWebSecurityExpressionRoot
2.添加getIdUrlPathParameter()方法。它将有权访问HttpServletRequest对象。
3.定义CustomWebSecurityExpressionHandler,以扩展
DefaultWebSecurityExpressionHandler
。覆盖createSecurityExpressionRoot方法,然后在此处使用CustomWebSecurityExpressionRoot。
4.定义自定义访问决策管理器(下面的xml)
5. 通过access-decision-manager-ref属性将其注入到 http 元素中

<security:http access-decision-manager-ref="customAccessDecisionManagerBean" >
    <security:intercept-url pattern="/user/{id}/edit" access="getIdUrlPathParameter() == principal.userId"/>
</security:http>
<bean id="customWebSecurityExpressionHandler" class="com.domain.security.CustomWebSecurityExpressionHandler"/>
<bean id="customAccessDecisionManagerBean" class="org.springframework.security.access.vote.AffirmativeBased">
    <property name="decisionVoters">
        <list>
            <bean class="org.springframework.security.web.access.expression.WebExpressionVoter">
                <property name="expressionHandler" ref="customWebSecurityExpressionHandler" />
            </bean>
        </list>
    </property>
</bean>
2020-06-01