title: How to prevent redirecting unauthenticated users to login page in Spring Security?
body: <p>The web application I am working on uses Spring Security. I configured it so that unauthorized requests are handled by one of controllers (using <code>access-denied-handler</code>). 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.</p>
  
  <p>There has been a <a href="https://stackoverflow.com/questions/15847932/prevent-redirect-to-login-for-spring-security">similar question</a> 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.</p>
  
  <p>Here is what my security configuration roughly looks like:</p>
  
  <pre><code>&lt;http use-expressions="true" pattern="/**" authentication-manager-ref="operatorAuthenticationManager"&gt;
      &lt;access-denied-handler error-page="/denied" /&gt;
  
      &lt;intercept-url pattern="/order/**" access="hasAnyAuthority('ROLE_ADMIN','ROLE_OPERATOR')"/&gt;
      &lt;intercept-url pattern="/client/**" access="hasAnyAuthority('ROLE_ADMIN')"/&gt;
      &lt;intercept-url pattern="/denied" access="permitAll"/&gt;
      &lt;intercept-url pattern="/login" access="permitAll"/&gt;
      &lt;intercept-url pattern="/login.jsp" access="permitAll"/&gt;
      ...
      &lt;intercept-url pattern="/**" access="hasAnyAuthority('ROLE_ADMIN','ROLE_OPERATOR')"/&gt;
  
      &lt;form-login login-page="/login" default-target-url="/" always-use-default-target="true"
                  authentication-success-handler-ref="operatorAuthenticationSuccessHandler" authentication-failure-url="/login?error"/&gt;
      &lt;logout logout-success-url="/login"/&gt;
  &lt;/http&gt;
  </code></pre>