Not getting message in spring internal exception

Viewed 235

Using Spring Boot with JWT and sprin security..when any exception thrown from servlet filter like unauthorized,forbidden. No getting message in response. when printing stack trace its showing but not getting in final response

{
    "timestamp": "2020-11-26T09:09:21.684+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/api/users/profile"
}

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String header = request.getHeader(JwtConstant.AUTHORIZATION);

        if (StringUtils.isNotBlank(header) && header.startsWith(JwtConstant.BEARER)) {

            String authToken = header.replace(JwtConstant.BEARER, "");
            Claims claims = jwtTokenUtil.getJwtClaims(authToken);

            String username = claims.getSubject();

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
                    "", getAuthoritiesFromString(claims));

            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);

        }

        filterChain.doFilter(request, response);
    }

public Claims getJwtClaims(String token) {

        Claims claims = null;

        try {
            claims = Jwts.parserBuilder().setSigningKey(getPublicKey()).build().parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            throw new CustomException(env.getProperty(ExceptionMessage.TOKEN_EXPIRED),e, ErrorCode.TOKEN_EXPIRE);
        } catch (SignatureException | MalformedJwtException e) {
            throw new CustomException(env.getProperty(ExceptionMessage.TOKEN_INVALID),e, ErrorCode.TOKEN_INVALID);
        } catch (Exception e) {
            throw new CustomException(env.getProperty(ExceptionMessage.TOKEN_PARSING),e, ErrorCode.INTERNAL_SERVER_ERROR);
        }

        return claims;
    }

i am using jwt authentication. when request contains token. then first i am getting claims from token. but if token is expired,invalid then i want to throw custom exception..but i am not able to get custom exception code and message

1 Answers

This is caused by the changes made in SpringBoot since 2.3 Release. See this section. Error messages are no longer included in responses by default. Add this line to your application.properties:

server.error.include-message=always
Related