DEV Community

ronnyjubhari
ronnyjubhari

Posted on

How return a JSON response instead of an HTML error code like 401 or 400

Hello guys, i need help

with following the tutorial in this link β€˜https://medium.com/geekculture/implementing-json-web-token-jwt-authentication-using-spring-security-detailed-walkthrough-1ac480a8d970’, i can create jwt token authorization but how to return json response instead of an HTML error code like 401 or 400 when the JWT token is not valid, expired, or not used ?

Image description

Image description

Top comments (1)

Collapse
 
envitab profile image
Ekemini Samuel

Hey @ronnyjubhari

To return a JSON response instead of an HTML error code like 401 or 400 in Spring Boot, you can use a custom error handler.

Try this steps:

  1. First, create a function or method in your Spring Boot application that handles the JWT token validation and generates the JSON response for JWT-related errors.

  2. Implement a custom exception class, such as InvalidTokenException or ExpiredTokenException, to represent different JWT-related errors.

  3. Create a custom exception handler using the @ControllerAdvice and @ExceptionHandler annotations to handle these JWT-related exceptions.

  4. Within the custom exception handler, construct a JSON response with appropriate error messages and status codes for each type of JWT-related error.

  5. Make sure to configure Spring Security to use your custom exception handler to handle JWT-related errors.

  6. Test your implementation by sending requests with invalid, expired, or unused JWT tokens to see the JSON responses in action.

If you encounter any issues, feel free to ask for further assistance.

Good luck, and happy coding! πŸ‘¨πŸΎβ€πŸ’»πŸš€