Spring MVC PreAuthorize and private/final methods

Spring MVC has nice feature for adding security controls to Controller methods via @PreAuthorize annotation, but there’s an interesting problem that might occur when those methods are mistakenly marked as private or final.

Spring uses CGLib proxy to add calls to authorization logic declared in @PreAuthorize before calling actual controller method, but CGLib fails to process private or final methods, producing error like this in console:

2016-11-28 17:19:14.186 INFO 97079 --- [ main] o.s.aop.framework.CglibAopProxy : Unable to proxy method [public final java.util.Map com.package.controller.MyController.someMethod(javax.servlet.http.HttpServletResponse)] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.

Well, so far so good – nothing special happens, all is more/less expected.

The problem though is that among most console output produced by Spring MVC yet another INFO log line rarely gets noticed. So what actually happens with those private/final methods of SpringMVC controller? Here weird stuff begins.

Say you’re writing a controller method that has a @PreAuthorize added to it, and accidentally copy-paste in a return type with final predicate before it, thus making your method final. You miss the log line in console because it’s just INFO among many other similar lines. And then… all autowired or otherwise injected fields of a controller are somehow null when calling only that particular method. But we know that in Spring MVC every controller is a singleton, so how is this even possible?

The issue appears to be that we’re actually calling methods on a CGLib proxy, that can’t pass them down to actual controller class instance. But proxy itself looks just like the controller class instance, except all fields that were supposed to be injected by Spring are null. A weird looking symptom which does not intuitively lead us to the cause of the problem.

But once one encounters this issue, I bet one remembers well next time what it is a symptom of.

P.S. I’ve encountered this issue with final method, but seems other people had same issue with private methods.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s