首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

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

2012-08-27 
当SpringSecurity可以在Ajax调用时返回401为了省事和配置文件的干净,SpringSecurity是用的namespace方式声

当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方法:

@Overridepublic 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" value="/login" />
</beans:bean>

热点排行