Friday, May 23, 2014

Why @Secured and @PreAuthorize isn't working?

As mention in the title, I'm so curious to know why the both annotation are not working? Since there were so many examples and tutorials available on the Internet, but why none of them showing me that configuring Spring Security in such a way isn't a wise move? Which way? The finding is as follow.

As according to the Spring MVC development standard, the Spring Security configuration and servlet configuration were separated. Thus I was thinking that those security stuff together with <global-method-security> must be separated out from regular Spring configuration module and put them in Spring security configuration module.

To make the picture clearer. I have the Spring security configure in such a way:

 
 

  
   
   
  
   ...
  
   

   ...
   
  

  
  
   
   

   ...

  
 

And those non security stuff would place in regular Spring configuration module shown as below:


   

   
      
         /WEB-INF/pages/
      

      
         .jsp
      
   

And last, I have both Spring configuration declare in web.xml


   ...

   
      contextConfigLocation
      
         /WEB-INF/security.xml
         /WEB-INF/datasource.xml
         /WEB-INF/WebEngineering-servlet.xml
      
   

...


Everything were run perfect and no error. Just that @Secured will never work. Initially I though there is a bug in @Secured for Spring Security 3.1, but this is not true because the annotation were still not working even though I have upgraded to Spring Security 3.2. Someone in the forum suggest me to use @PreAuthorize simply because @PreAuthorize is newer than @Secured. I tried that, unfortunately @PreAuthorise is still working. I have tried many ways, keep searching the solutions, reading the same article again and again to make sure I didn't miss out the important point. Until my last try before I nearly give up (and before I start blaming Spring framework), I take out <global-method-security> from Spring security module, and put it in the regular Spring configuration module.

And it works!!

So this is the final amendment I made on the regular Spring configuration:


   
   

   
      
         /WEB-INF/pages/
      

      
         .jsp
      
   

And now both @Secured and @PreAuthorize are living in my code happily ever after. :)

3 comments:

Alvaro Costa said...

Hi,
Thank you for sharing this solution, it worked for me. :)
Have a nice day !

Андрей Дуплык said...

Thank you, it worked!

pradip garala said...

Thank you for saving my time.

It worked for me.