Skip to content
Advertisement

spring security with jwt token returns 401 html page not json

why spring returns 401 html page instead of my custom json api response with error? and what is the best way to fix it (override spring config)

security:

JavaScript

Filter:

JavaScript

so i implemented custom exception handler and filter, and what i need is this type of error

JavaScript

that what i get when login fo example, success case to get token is also working

JavaScript

but whey for example token is not correct or expired or so, i get 401 unauthorized (correct) but instead of json with message that i set up i get full html page with error

JavaScript

Advertisement

Answer

For custom JSON error block, you need to do two things

  1. Implement the AuthenticationEntryPoint

    public class AuthExceptionEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException, ServletException {

    JavaScript

    }

and add that reference in the websecurity settings configure(HttpSecurity http)

JavaScript

check these two resources for more details

JSON custom authentication

JSON custom error response

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement