Rest call on expired session: HTTP 401 response causes browser to display login window

人盡茶涼 提交于 2019-12-03 06:54:02

I finally found the solution for this. As I mentioned in my update the reason is, that the response contains the WWW-Authenticate header field. My solution was then to change the configuration of spring security to return a different header:

WWW-Authenticate: FormBased

To do this I had to implement the AuthenticaitonEntryPoint interface and manually set the header and status code in the response:

@Component( "restAuthenticationEntryPoint" )
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence( HttpServletRequest request, HttpServletResponse response,
                          AuthenticationException authException ) throws IOException {
        response.setHeader("WWW-Authenticate", "FormBased");
        response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
    }
}

then I changed the configuration of spring-security and set the entry-point-ref to point to the new class:

<http pattern="/rest/**" create-session="never" entry-point-ref="restAuthenticationEntryPoint">
    <intercept-url pattern="/rest/**" access="ROLE_USER" />
    <http-basic />
    <session-management />
</http>

If you want to avoid changing the server and make it return WWW-Authenticate header for all other callers, you can change your client to send its request with X-Requested-With header with XMLHttpRequest value. By default, Spring Security will not to send WWW-Authenticate for such requests. (see Spring source)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!