It had been a while since I read about Spring Security. Now that I was trying to create a new booking I had to retrieve the currently logged in user to be able to add the new booking to that user's bookings. So I thought I'd just slap a
<global-method-security secured-annotation="enabled" />
in my application-security.xml and then add a
@Secured("ROLE_USER")
on my method that was mapped to ("/") and Spring should pop up a login form for me when accessing that URL. But unfortunately it didn't work that easily. The page showed up just like before, with no login form in sight. So I went back to reading the Spring Security manual and looking for some posts on Spring's forums and after a while I noticed that other people had solved similar problems by putting the
global-method-security
element in the same xml file as the one where they set up their
Controller
beans. Since I use the
component-scan
element to automatically instantiate my
@Controller
-annotated classes in my
servletname-servlet.xml file, I thought I'd just move the
global-method-security
element to that file. At first I got a long spew of exceptions and call traces, but that was just related to some incorrectly configured xml namespaces. When I sorted that out Spring Security finally worked.
The exercise also straightened out one misconception I had about spring. I thought the
DispatcherServlet
's
servletname-servlet.xml file created a new application context that was separate from the
WebApplicationContext
which Spring's context loader sets up. But then I found this in the Spring manual
"In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext." However I still don't understand why the
DispatcherServlet
context didn't inherit the
global-method-security
element from my
WebApplicationContext
which contained my security beans.