[英]Spring Boot Security JWT custom authentication error messages
如何在 JWT 身份验证失败时发送不同的错误消息? 我尝试了下面的代码,它总是发送消息为: Full authentication is required to access this resource
而不是我想使用来自异常的 errorMessage。 我正在使用 spring boot 3(如果重要的话)
WebSecurityConfig.class:
@Bean
public AuthenticationEntryPoint restAuthenticationEntryPoint() {
return (request, response, error) -> {
log.info("restAuthenticationEntryPoint: {}", error.getMessage(), error);
Map<String, Object> errorObject = new HashMap<>();
int errorCode = 401;
errorObject.put("message", error.getMessage());
errorObject.put("error", HttpStatus.UNAUTHORIZED);
errorObject.put("code", errorCode);
errorObject.put("timestamp", new Timestamp(new Date().getTime()));
response.setContentType("application/json;charset=UTF-8");
response.setStatus(errorCode);
response.getWriter().write(objectMapper.writeValueAsString(errorObject));
};
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.formLogin()
.disable()
.httpBasic()
.disable()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint())
.and()
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
在 JWT 验证中,我抛出了不同的消息,但客户端仍然收到相同的错误消息。
public DecodedJWT decodeJWT(String authToken) {
try {
return verifier.verify(authToken));
} catch (SignatureVerificationException e) {
log.error("Invalid JWT signature: {}", e.getMessage());
throw new TokenException(e.getMessage());
} catch (TokenExpiredException e) {
log.error("JWT token is expired: {}", e.getMessage());
throw new TokenException(e.getMessage());
} catch (MissingClaimException e) {
log.error("JWT token is unsupported: {}", e.getMessage());
throw new TokenException(e.getMessage());
} catch (JWTDecodeException e) {
log.error("JWT claims string is empty: {}", e.getMessage());
throw new TokenException(e.getMessage());
} catch (AlgorithmMismatchException | IncorrectClaimException e) {
log.error("JWT alg mismatch or incorrect claim : {}", e.getMessage());
throw new TokenException(e.getMessage());
} catch (InvalidClaimException e) {
log.error("InvalidClaimException");
throw new TokenException(e.getMessage());
} catch (JWTVerificationException e) {
log.error("JWTVerificationException at end");
throw new TokenException(e.getMessage());
}
}
令牌异常类:
public class TokenException extends AuthenticationException {
public TokenException(String msg, Throwable cause) {
super(msg, cause);
}
public TokenException(String msg) {
super(msg);
}
}
此异常从 tokenAuthenticationFilter 类中抛出。 请注意,即使发生异常,过滤器类也不会停止。 您的过滤器类将忽略您的异常。
发生异常时如何停止? 当你调用 decodeJwt(); 方法。 您应该将此方法放在 try-catch 中。 如果捕获到异常,那么你应该调用 sendError(); 来自 HttpServletResponse 类的方法并返回; 方法。
添加返回; 即使方法无效
DecodedJWT decodedJWT = null;
try {
decodedJWT = jwtUtils.decodeJWT(token);
} catch(Exception e) {
response.sendError(401, e.getMessage);
return;
}
将上面的代码添加到您的过滤器类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.