Spring Boot 和 Spring Security,无法在 AuthenticationEntryPoint 中发送带有自定义消息的错误



我正在使用spring-boot开发一个restful api,并将使用自定义authenticationEntryPoint。这是代码

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
}

以及安全配置中的相关部分。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
...
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.GET, "/api/users/checkUsernameAvailability", "/api/users/checkEmailAvailability").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
...
}

问题是,当我使用错误的凭据登录时,错误消息为空。

{
"timestamp": "2020-09-03T17:16:28.082+00:00",
"status": 401,
"error": "Unauthorized",
"message": "",
"path": "/api/auth/signin"
}

但是,记录器打印正确的消息

c.m.p.s.JwtAuthenticationEntryPoint      : Responding with unauthorized error. Message - Bad credentials

这里可能出了什么问题?提前谢谢。

server.error.include-message的默认值为"never"

因此,你只需要像这个一样配置你的application.yaml(或属性(

server:
error:
include-message: always
include-binding-errors: always

最新更新