jantobola
jantobola

Reputation: 688

Spring Security - redirect to specific url after intercept-url access fails

I have these rules to access pages in my app:

<http auto-config="true" use-expressions="true">
        <!-- NON AUTHENTICATION PAGES -->
        <intercept-url pattern="/" access="permitAll" />
        <intercept-url pattern="/about" access="permitAll" />       

        <!-- LOGIN FILTER -->
        <intercept-url pattern="/login" access="!isAuthenticated()" />
        <intercept-url pattern="/j_spring_security_check" access="!isAuthenticated()" />
        <intercept-url pattern="/logout" access="!isAuthenticated()" />

        <!-- RESOURCES AND OTHER URLs FILTER -->
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />

        <!-- FORM LOGIN -->
        <form-login login-page="/login" default-target-url="/upload" authentication-failure-url="/loginfailed"  />
        <logout logout-success-url="/logout" />
    </http>

and what I need is to redirect to some url (e.g. /access-denied) when access fails and handle this event in controller.

@RequestMapping(value = "/access-denied", method = RequestMethod.GET)
    public String accessDenied(Model model, RedirectAttributes ra) {

    // do what I want

    return "redirect:login";
}

For example user enters /upload and he is not logged in so it will be redirected to /access-denied.

Upvotes: 0

Views: 10362

Answers (2)

Vishnu G S
Vishnu G S

Reputation: 714

Notice the access-denied-page attribute in security-http in code that follows.

<security:global-method-security
            pre-post-annotations="enabled" />
    <security:http auto-config="false" use-expressions="true"
            disable-url-rewriting="true" entry-point-ref="loginUrlAuthenticationEntryPoint"
            access-denied-page="/access-denied">
        <security:intercept-url pattern="/someurl"
                access="isAuthenticated()" />
</security:http>

Upvotes: 0

Shaun the Sheep
Shaun the Sheep

Reputation: 22762

It might help to explain why you need to do the redirect yourself, since Spring Security will do this automatically. When access is denied, the default behaviour for an unauthenticated user, is to redirect them to the login page (which seems to be what you want to do).

If you want to customize the process, the strategy used is the AuthenticationEntryPoint it would probably make more sense to implement this than to use a controller. I've written more about this in a previous answer.

If you just want to slot in some extra functionality, you can extend LoginUrlAuthenticationEntryPoint and override the commence method, calling the superclass to do the redirect.

Note that this means the login-page value from the namespace element won't be used. You'll need to set the login URL in the constructor for LoginUrlAuthenticationEntryPoint.

Upvotes: 2

Related Questions