简体   繁体   English

Spring Boot Security JWT 自定义身份验证错误消息

[英]Spring Boot Security JWT custom authentication error messages

How to send different error messages on JWT authentication failure?如何在 JWT 身份验证失败时发送不同的错误消息? I tried below code, its always sending message as: Full authentication is required to access this resource instead I want to use errorMessage from exception.我尝试了下面的代码,它总是发送消息为: Full authentication is required to access this resource而不是我想使用来自异常的 errorMessage。 I am using spring boot 3 (if it matters)我正在使用 spring boot 3(如果重要的话)

WebSecurityConfig.class: 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();
}

At JWT validation, I am throwing different messages, still client is receiving same error message.在 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());
    }
}

TokenException class:令牌异常类:

public class TokenException extends AuthenticationException {
 public TokenException(String msg, Throwable cause) {
    super(msg, cause);
 }

 public TokenException(String msg) {
    super(msg);
 }
}

This exception throws from tokenAuthenticationFilter class.此异常从 tokenAuthenticationFilter 类中抛出。 Note that the filter class won't stop even if an exception occurs.请注意,即使发生异常,过滤器类也不会停止。 Your filter class will just ignore your exception.您的过滤器类将忽略您的异常。

How to stop when exception occurs?发生异常时如何停止? When you're calling decodeJwt();当你调用 decodeJwt(); method.方法。 You should put this method inside try-catch.您应该将此方法放在 try-catch 中。 If exception is catched then you should call sendError();如果捕获到异常,那么你应该调用 sendError(); method from HttpServletResponse class and put return;来自 HttpServletResponse 类的方法并返回; method.方法。

Add return;添加返回; even method is void即使方法无效

DecodedJWT decodedJWT = null;
try {
  decodedJWT = jwtUtils.decodeJWT(token);
} catch(Exception e) {
  response.sendError(401, e.getMessage);
  return;
}

add this code above to your filter class将上面的代码添加到您的过滤器类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM