Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return response as Json from spring filter?

In spring rest I need to send authentication error from doFilter() of my filter class. In response i need to send json with fields like status, message and errorCode. Kindly suggest how to achieve. We are not using spring boot.Below is the sample response on Authentication error

{ "responseCode":" Error code", "responseMessage": "Some Error message", "responseStatus":"Fail" }

Inside doFiler(), i am validating token, if its not valid I need to send above sample response.

like image 545
Diana Avatar asked Dec 01 '22 13:12

Diana


1 Answers

Assuming you have Jackson's ObjectMapper exposed as a Spring bean, you could use the following for a OncePerRequestFilter:

@Component
@RequiredArgsConstructor
public class MyFilter extends OncePerRequestFilter {

    private final ObjectMapper mapper;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws IOException {

        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("message", "Invalid token");

        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        mapper.writeValue(httpServletResponse.getWriter(), errorDetails);
    }
}

For a plain servlet Filter, the solution would be much the same:

@Component
@RequiredArgsConstructor
public class MyFilter implements Filter {

    private final ObjectMapper mapper;

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException {

        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("message", "Invalid token");

        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        mapper.writeValue(httpServletResponse.getWriter(), errorDetails);
    }

    @Override
    public void destroy() {

    }
}

The above examples rely on constructor injection and use Lombok's @RequiredArgsConstructor to generate a constructor that receives values for the fields marked with final.

You also could replace the Map<String, Object> for any arbitrary POJO, according to your needs.

like image 179
cassiomolin Avatar answered Dec 05 '22 10:12

cassiomolin