当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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值