Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use spring security to tell ajax requests where the login page is

I have some url secured with spring (configured through xml). It works. However when I try to hit that endpoint with an ajax request I get a 302 (found) response. This redirects my ajax call to the login page (so I GET the html). However I'd like to get a 401 (unauthorized) response with the url of the login page available to the client application, so I can redirect the user there with javascript. This question seems to be the closest to what I want, but there's no example and it suggests changing the controller again. Is there no configuration in spring-security that will give me a 401 and a url (or some other sensible error message and the url of the login page)?

like image 762
Josh Avatar asked Dec 04 '22 19:12

Josh


1 Answers

You can extend LoginUrlAuthenticationEntryPoint. Here is my one:

package hu.progos.springutils;
// imports omitted
public class AjaxAwareLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
        } else {
            super.commence(request, response, authException);
        }
    }
}

Then configure spring to use your implementation:

<beans:bean id="authEntryPoint" class="hu.progos.springutils.AjaxAwareLoginUrlAuthenticationEntryPoint" scope="singleton>
    <beans:property name="loginFormUrl" value="/login.html" />
</beans:bean>

<http entry-point-ref="authEntryPoint">
  <!-- your settings here -->
</http>
like image 64
arpad Avatar answered Dec 21 '22 23:12

arpad