1

The web application I am working on uses Spring Security. I configured it so that unauthorized requests are handled by one of controllers (using access-denied-handler). However, when someone tries accessing a page before logging in he finds himself at login page without passing through the controller. I want this case to be handled by the same controller as mentioned above.

There has been a similar question where REST API requests are handled by a controller and the remaining requests are redirected to login page. This was achieved using two Entry Points. What I want is for one cotroller to handle all unauthorized/unauthenticated request, be it service calls or static pages. So, I don't need two different mechanisms. Do I still need to configure an Entry Point? I suppose there should be an easier way of doing this.

Here is what my security configuration roughly looks like:

<http use-expressions="true" pattern="/**" authentication-manager-ref="operatorAuthenticationManager">
    <access-denied-handler error-page="/denied" />

    <intercept-url pattern="/order/**" access="hasAnyAuthority('ROLE_ADMIN','ROLE_OPERATOR')"/>
    <intercept-url pattern="/client/**" access="hasAnyAuthority('ROLE_ADMIN')"/>
    <intercept-url pattern="/denied" access="permitAll"/>
    <intercept-url pattern="/login" access="permitAll"/>
    <intercept-url pattern="/login.jsp" access="permitAll"/>
    ...
    <intercept-url pattern="/**" access="hasAnyAuthority('ROLE_ADMIN','ROLE_OPERATOR')"/>

    <form-login login-page="/login" default-target-url="/" always-use-default-target="true"
                authentication-success-handler-ref="operatorAuthenticationSuccessHandler" authentication-failure-url="/login?error"/>
    <logout logout-success-url="/login"/>
</http>
Community
  • 1
  • 1
Limbo Exile
  • 1,321
  • 2
  • 21
  • 41

1 Answers1

3

An entry point is:

where the authentication process is triggered by an attempt by an unauthenticated user to access to a secured resource

With that being said, an entry point bean fits perfectly to your requirements.

In your entry point, you can define a redirect to your error page.

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

   @Override
   public void commence( HttpServletRequest request, HttpServletResponse response, 
    AuthenticationException authException ) throws IOException{
      //your implementation
   }
}

The example above shows that you'll need to figure out how to do redirect with HttpServletReponse, here's a link that shows how to do it:

HttpServletResponse sendRedirect permanent

Community
  • 1
  • 1
Moshe Arad
  • 3,587
  • 4
  • 18
  • 33