当SpringSecurity可以在Ajax调用时返回401

为了省事和配置文件的干净,SpringSecurity是用的namespace方式声明的。

namespace方式有个麻烦在于很多配置固定而不好改变。
现在 有个需求是让Ajax的JSON调用返回的401以便前端JS可以识别status来刷新页面。

查文档和看源码后,终于有这个方案:
<http>创建的ExceptionTranslatorFilter在检测到 权限异常时,
会调用EntryPoint的commence方法。
<form-login />的后台处理会建立一个EntryPoint : LoginUrlAuthenticationEntryPoint,
<http>的解析代码,在没有指定EntryPoint时,使用<form-login>等tag创建的EntryPoint。
因此,重载LoginUrlAuthenticationEntryPoint的commence方法:
@Override
	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		if (StringUtils.contains(request.getHeader("Accept"), "application/json")) {
        	response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 
        			"Authentication Failed: " + authException.getMessage());
        } else {
        	super.commence(request, response, authException);
        }
	}

最后,修改相关的applicationContext文件:
<http use-expressions="true" auto-config="false" entry-point-ref="myEntryPoint">
....
</htt>
<beans:bean id="myEntryPoint" class="com.yunling.mediacenter.man.MyLoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login" />
</beans:bean>

猜你喜欢

转载自dwangel.iteye.com/blog/1150338