gpt4 book ai didi

java - Spring Boot 和 Spring Security,无法在 AuthenticationEntryPoint 中使用自定义消息发送错误

转载 作者:行者123 更新时间:2023-12-05 00:45:25 25 4
gpt4 key购买 nike

我正在使用 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

关于java - Spring Boot 和 Spring Security,无法在 AuthenticationEntryPoint 中使用自定义消息发送错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63730436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com