使用JSON响应处理Spring安全性错误

Zem*_*ela 5 spring spring-mvc spring-security

我正在使用spring security 3.1和Spring 3.2来进行REST服务.我正在努力使每个响应都是JSON,例如,如果用户尝试访问某些资源但尚未经过身份验证.此外,如果用户提出错误请求,我想返回带有错误消息的JSON.

仅仅提一下,我可以更容易地获得一些全局的地方,我应该抓住所有的错误/例外.

sha*_*ltc 3

为什么不编写一个由所有其他控制器扩展的控制器类(或者在使用 3.2 的情况下使用 @ControllerAdvice)并在该类中包含一个异常处理程序注释方法?像这样的东西

@ExceptionHandler(Throwable.class)
public @ResponseBody GenericResponse handleException(Throwable throwable){
 //handle exception

 }
Run Code Online (Sandbox Code Playgroud)

或者阅读这篇博

更新

抱歉这么晚回复。这是我的建议。让它简单地失败并返回 403 响应。为此,只需在 Spring 安全配置中添加以下代码片段即可。

<beans:bean id="entryPoint"
    class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
Run Code Online (Sandbox Code Playgroud)

并将入口点引用指向该 bean

<http auto-config="true" use-expressions="true" entry-point-ref="entryPoint">
Run Code Online (Sandbox Code Playgroud)

在客户端的 AJAX 代码中,添加一个错误块

            error : function( jqXHR, textStatus, errorThrown ){
                if (jqXHR.status == 403){
                    alert('you need to login to do this operation');
                    window.location.href = contextPath+"/signin";
// or whatever you want to
                }
            }
Run Code Online (Sandbox Code Playgroud)

  • 不能解决我的问题,不能捕获错误的请求。也许是因为 Spring 安全性。无法接受这个答案是正确的。 (3认同)