无法为 url 模式验证 Spring 安全性中的角色

Unable to validate role in Spring Security for url pattern

我正在使用 spring 安全 3.1.7.RELEASE 和 spring 3.2.13.RELEASE.

我的 spring-security.xml 中有如下条目:

<http auto-config="true" use-expressions="true"> 
    <intercept-url pattern=".*admin.htm" access="hasRole(ROLE_ADMIN)" />
    <intercept-url pattern="/siteadmin/*.htm" access="ROLE_ADMIN" />
    <intercept-url pattern="/siteadmin/cleancache.htm" access="hasRole('ROLE_ADMIN')" />

当我尝试点击 url /siteadmin/cleancache.htm 时出现以下异常:

java.lang.IllegalArgumentException: Failed to evaluate expression 'ROLE_ADMIN' org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:13) org.springframework.security.web.access.expression.WebExpressionVoter.vote(WebExpressionVoter.java:34) org.springframework.security.web.access.expression.WebExpressionVoter.vote(WebExpressionVoter.java:18) org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:62)

Root Cause:

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'ROLE_ADMIN' cannot be found on object of type 'org.springframework.security.web.access.expression.WebSecurityExpressionRoot' - maybe not public? org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:214) org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:85) org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:78) org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102) org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:98) org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:11) org.springframework.security.web.access.expression.WebExpressionVoter.vote(WebExpressionVoter.java:34)

非常感谢任何关于相同的指示。

你有几个错别字。第一行 intercept-url 缺少围绕 ROLE_ADMIN 的单引号,第二行缺少 hasRole。应该是

<http auto-config="true" use-expressions="true"> 
    <intercept-url pattern=".*admin.htm" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/siteadmin/*.htm" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/siteadmin/cleancache.htm" access="hasRole('ROLE_ADMIN')" />

官方安全文档 spring 提供了您放置的示例:

<Intercept-url pattern = "/ siteadmin / *. Htm" access = "ROLE_ADMIN" />

但你应该穿

<Intercept-url pattern = ". * Admin.htm" access = "hasRole ('ROLE_ADMIN')" />