在寻找this问题的答案时,我一直在尝试根据IP地址过滤请求的方法。 我有以下方法:
@RequestMapping(value = "/payment", method = POST)
@PreAuthorize("hasIpAddress('XXX.XXX.X.XX')")
public String pay(PaymentDto paymentDto){
System.out.println("Payment received");
return "OK";
}
然而,在执行时,这会引发错误:
{"errorMessage":"Internal Server Error","errorId":"26b1a1ba-3ae8-4497-9f1c-7370ea5116ff","errorDetails":{"message":"Failed to evaluate expression 'hasIpAddress('XXX.XXX.X.XX')'","exception":"java.lang.IllegalArgumentException","errors":null}}
发生了什么事?
这是Java错误:
org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 0): Method call: Method hasIpAddress(java.lang.String) cannot be found on org.springframework.security.access.expression.method.MethodSecurityExpressionRoot type
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:211) ~[spring-expression-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:125) ~[spring-expression-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:85) ~[spring-expression-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:131) ~[spring-expression-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
答案 0 :(得分:5)
Doc,hasIpAddress是Web安全表达式,不适用于@PreAuthorize。 你可以像这样使用
<http use-expressions="true">
<intercept-url pattern="/admin*"
access="hasRole('admin') and hasIpAddress('xxx.xx.xx.xxx')"/>
...
</http>
或
http
.authorizeRequests()
.antMatchers("/tokens").access(
"hasIpAddress('xxx.x.xx.xx'))
但不是
@PreAuthorize("hasIpAddress('XXX.XXX.X.XX')")
public String pay(PaymentDto paymentDto){