Spring Security, Spring MVC, PreAuthorise annotation and exception handling

420 views Asked by At

I'm struggling with Spring Security and exception handling.

I have the following exception handler configured in my servlet-context:

   <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="/errors/general-error"/>
        <property name="defaultStatusCode" value="500" />
        <property name="warnLogCategory" value="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"/>
    </bean>

This catches any uncaught exceptions, and shows a general error page.

I also have Spring Security configured using a CAS single sign on server. If in my Security configuration I have the following:

<security:intercept-url pattern="/secure/**" access="hasRole('USER')" />

If an unauthenticated user visits "/secure", they are correctly redirected to login, then they return and can view the page.

I'd prefer to use PreAuthorise() annotations on the MVC methods, rather than having to define the URLs manually. So instead, if I have the following annotation:

    @PreAuthorize("hasRole('USER')")
    @RequestMapping("/secure")
    public String displaySecurePage(
...
}

The redirect to the CAS SSO server doesn't happen, and Spring simply displays the general error page, with an Exception org.springframework.security.access.AccessDeniedException: Access is denied

Why is there a difference between the two ways of defining the access permissions, and how can I use the PreAuthorise annotation with Spring correctly directing an unauthenticated user to login, and still have a exception handler to catch other exceptions?

0

There are 0 answers