How to do the type casting in Spring expression language
Asked Answered
F

2

10

I'm trying to use the @PreAuthorize annotation for access control. I need to check some custom fields in the details of the authentication object. I have a CustomWebAuthenticationDetails class, which is a subclass of WebAuthenticationDetails and contains custom fields. Normally, I would use the following to get to my custom fields in CustomWebAuthenticationDetails:

((CustomWebAuthenticationDetails)authentication.getDetails()).getCustomField()

However, when I try to use the above statement (even including the fully qualified path to CustomWebAuthenticationDetails) in the @PreAuthorize expression, I get the following error:

java.lang.IllegalArgumentException: Failed to parse expression ...

How am I supposed to do with the type casting here?

Thanks,

Daniel

Favored answered 9/6, 2012 at 2:56 Comment(0)
S
16

AFAIK, given the dynamic and interpreted nature of EL, you don't need any cast. If the property exists for the runtime object, it will find it, without caring about its declared type:

authentication.details.customField
Sausa answered 9/6, 2012 at 6:59 Comment(0)
A
1

Although I wouldn't disagree with the accepted answer, there may be instances where an explicit cast is preferred. Two reasons why this may be preferable is:

  • readability - those reading the SpEL expression will know the object type instantly
  • error handling - an invalid cast will throw an exception in template parsing, rather than a runtime exception at a later point

The cleanest way to type cast in SpeL is using the java.lang.Class.cast() method as follows:

CustomWebAuthenticationDetails.cast(authentication.getDetails()).getCustomField()

which represents a workaround to the java type conversion syntax you attempted above not working in SpEL (Spring Expression Language).

Amalle answered 8/7, 2022 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.