栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Boot REST API / Spring Security:身份验证失败时返回自定义消息

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot REST API / Spring Security:身份验证失败时返回自定义消息

WebSecurityConfigurerAdapter方法

HttpSecurity
类有一个叫做方法exceptionHandling可用于覆盖默认行为。以下示例介绍了如何自定义响应消息。

@Overrideprotected void configure(HttpSecurity http) throws Exception {    http        // your custom configuration goes here        .exceptionHandling()        .authenticationEntryPoint((request, response, e) -> { String json = String.format("{"message": "%s"}", e.getMessage()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json);  });}

@ControllerAdvice方法-为什么在这种情况下不起作用

最初,我想到的

@ControllerAdvice
是捕获整个应用程序的身份验证异常。

import org.springframework.http.HttpStatus;import org.springframework.security.core.AuthenticationException;@ControllerAdvicepublic class AuthExceptionHandler {    @ResponseStatus(HttpStatus.UNAUTHORIZED)    @ExceptionHandler(AuthenticationException.class)    @ResponseBody    public String handleAuthenticationException(AuthenticationException e) {        return String.format("{"message": "%s"}", e.getMessage());    }}

在上面的示例中,JSON是手动构建的,但是您可以简单地返回一个POJO,该POJO将被映射到JSON中,就像从常规REST控制器中一样。既然Spring
4.3,你也可以使用@RestControllerAdvice,这是一个组合

@ControllerAdvice
@ResponseBody

但是,这种方法行不通,
因为在到达任何控制器之前,该异常将由抛出

AbstractSecurityInterceptor
并由ExceptionTranslationFilter处理。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号