Search code examples
spring-mvcspring-securityaccess-denied

Spring Security: access-denied-handler doesn't forward to error page


I'm fresh off the boat to Spring Security so excuse me if this seems awfully trivial..

I try to put the Spring Security mechanism in my MVC project, but for some reason the access-denied-handler doesn't send my unauthorized user to the denied access page and instead chooses to present the login page.

Here is my Http tag in the security-context.xml:

<http authentication-manager-ref="dao-auth"
    access-decision-manager-ref="accessDecisionManager"
    disable-url-rewriting="true">
    <intercept-url pattern="/pages/home.html" access="USER"></intercept-url>
    <intercept-url pattern="/home" method="GET" access="USER"></intercept-url>
    <intercept-url pattern="/logout" access="USER"></intercept-url>
    <intercept-url pattern="/denied" access="ROLE_ANONYMOUS"></intercept-url>
    <intercept-url pattern="/error" access="ROLE_ANONYMOUS,USER"></intercept-url>
    <intercept-url pattern="/"  access="ROLE_ANONYMOUS,USER"></intercept-url>
    <intercept-url pattern="/pages/**" access="ROLE_ANONYMOUS,USER"></intercept-url>
    <intercept-url pattern="/resources/**" access="ROLE_ANONYMOUS,USER"></intercept-url>
    <form-login login-page="/login" authentication-failure-url="/denied" 
        default-target-url="/home" />
    <logout invalidate-session="true" logout-success-url="/"
        logout-url="/logout" />
    <access-denied-handler error-page="/denied" />
    <session-management invalid-session-url="/login">
        <concurrency-control max-sessions="1"
            expired-url="/login" />
    </session-management>
</http>

Basically the way I test it is I try to access the /home path from the ROLE_ANONYMOUS user and instead get thrown to the /login one.

Also, can't figure out how to debug this thing or where I find the logs (feels like there are somewhere out there..)

Thanks to all responders :)


Solution

  • 1.Spring security looks for Authentication object in security context first. If there is no authentication object (basically a principal) found in the security context, it will direct you to the login page.

    2.If it finds Authentication object, then it will use the principal's authorities to do authorization.

    3.When Login screen is presented, the user entered credentials are authenticated and if not authenticated, then you can throw a bad credentials exception to show the access denied error.