我有一个ReST API到一个应用程序,其中找到了所有控制器/api/
,这些都返回JSON响应,@ControllerAdvice
其中处理所有异常以映射到JSON格式的结果.
这在春季4.0 @ControllerAdvice
现在支持匹配注释,效果很好.我无法解决的是如何返回401的JSON结果 - 未经验证和400 - 错误请求响应.
相反,Spring只是将响应返回给容器(tomcat),将其呈现为HTML.我如何拦截它并使用我@ControllerAdvice
正在使用的相同技术呈现JSON结果.
security.xml文件
<bean id="xBasicAuthenticationEntryPoint"
class="com.example.security.XBasicAuthenticationEntryPoint">
<property name="realmName" value="com.example.unite"/>
</bean>
<security:http pattern="/api/**"
create-session="never"
use-expressions="true">
<security:http-basic entry-point-ref="xBasicAuthenticationEntryPoint"/>
<security:session-management />
<security:intercept-url pattern="/api/**" access="isAuthenticated()"/>
</security:http>
Run Code Online (Sandbox Code Playgroud)
XBasicAuthenticationEntryPoint
public class XBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
authException.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过使用BasicAuthenticationEntryPoint
直接写入输出流来解决401 ,但我不确定这是最好的方法.
public class XBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
private final ObjectMapper om;
@Autowired …
Run Code Online (Sandbox Code Playgroud)