uksz
uksz

Reputation: 18719

Failed to evaluate expression 'hasIpAddress(..)' in PreAuthorize

In the pursuit of finding an answer to this question, I've been playing around with the ways to filter request based on the Ip Address. I have the following method:

@RequestMapping(value = "/payment", method = POST)
@PreAuthorize("hasIpAddress('XXX.XXX.X.XX')")
public String pay(PaymentDto paymentDto){
    System.out.println("Payment received");
    return "OK";
}

However, at execution, this throws me an error of:

{"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}} 

What is going on?

This is Java error:

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]

Upvotes: 5

Views: 3210

Answers (1)

Prasanna Kumar H A
Prasanna Kumar H A

Reputation: 3431

Doc, hasIpAddress is Web Security Expression and not available for @PreAuthorize. You can use like this

<http use-expressions="true">
    <intercept-url pattern="/admin*"
        access="hasRole('admin') and hasIpAddress('xxx.xx.xx.xxx')"/>
    ...
  </http>

or

http
    .authorizeRequests()
    .antMatchers("/tokens").access(
            "hasIpAddress('xxx.x.xx.xx'))

But not as

@PreAuthorize("hasIpAddress('XXX.XXX.X.XX')")
public String pay(PaymentDto paymentDto){

Upvotes: 7

Related Questions