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

Mil*_*ong 3 java spring spring-boot

我正在使用 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@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);
    }
    ...
}

Run Code Online (Sandbox Code Playgroud)

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

{
    "timestamp": "2020-09-03T17:16:28.082+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "",
    "path": "/api/auth/signin"
}
Run Code Online (Sandbox Code Playgroud)

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

c.m.p.s.JwtAuthenticationEntryPoint      : Responding with unauthorized error. Message - Bad credentials
Run Code Online (Sandbox Code Playgroud)

这里可能会出现什么问题?先感谢您。

Nem*_*nja 11

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

application.yaml因此,您只需要像这样配置您的(或属性)

server:
  error:
    include-message: always
    include-binding-errors: always
Run Code Online (Sandbox Code Playgroud)

  • @MillerDong 这取决于项目中使用哪个版本的 spring boot。自 Spring Boot 2.3 起,他们将“server.error.include-message”的默认值更改为“never” (2认同)