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

I have a url with spring (configured via xml). It is working. However, when I try to get to this endpoint using an ajax request, I get a 302 response (found). This redirects my ajax call to the login page (so that I get html). However, I would like to receive a 401 (unauthorized) response with the URL of the login page available for the client application, so I can redirect the user there using javascript. This question seems closest to what I want, but there is no example, and it suggests changing the controller again. Is there a configuration in spring-security that will give me 401 and url (or another reasonable error message and login page url)?

+4
source share
2 answers

You can extend LoginUrlAuthenticationEntryPoint. Here is my:

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> 
+16
source

There are, of course, a million ways to do this. But a short solution to your problem is a piece of configuration:

 <bean id="customAuthEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> <property name="loginFormUrl" value="/your-custom-login" /> </bean> 

I will also take another step and turn off the automatic security setting so that I can map the above entry point like this:

  <security:http auto-config="false" entry-point-ref="customAuthEntryPoint"> ... ... </security:http> 

I also override the spring class group to ensure that the security model does exactly what I want. It's a slippery slope, but it's nice to have control as soon as it works the way you want.

0
source

Source: https://habr.com/ru/post/1381755/


All Articles