设置: Tomcat 上的 Resteasy + Spring Security。 客户端/服务器之间交换的数据采用 JSON 格式。 当应用程序抛出任何异常时,让异常映射器返回 JSON 格式的消息。
目标: 每当出现问题时,始终从服务器返回格式正确的 JSON 错误消息。
发生了什么: Spring Security 层在 servlet 容器调用方法 foo() 之前被调用。如果这一层失败(例如错误的用户 ID),甚至在调用 servlet 之前就会抛出异常,因此错误的格式不正确。 知道如何解决这个问题并在这种情况下返回 JSON 错误吗?
谢谢。
如果有帮助,我的 web.xml 的一部分:
<filter>
<filter-name>securityPropagationFilter</filter-name>
<filter-class>com.foo.bar.context.servlet.SecurityContextPropagationFilter</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
<filter-name>loggingFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>securityPropagationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>loggingFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>
Resteasy
</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
最佳答案
我通过将以下内容添加到我的 web.xml 中解决了这个问题
<error-page>
<error-code>403</error-code>
<location>403.json</location>
</error-page>
另一方面,对于我需要处理的每个错误代码,我都需要一个条目。但我想如果我也必须在 Spring 中调整异常处理程序,我也必须这样做。
关于java - 过滤器链中 Spring security 抛出的格式化异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4739105/