Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot interceptor return JSON

I Have a spring boot application that is a REST Webservice.

I want to add an interceptor so that each role who doesn't have a permission for a specific action is returned with a 401 error code.

    @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

    logger.info("Request URL::" + httpServletRequest.getRequestURL().toString()
            + ":: Start Time=" + System.currentTimeMillis());

    UsernamePasswordAuthenticationToken token  = (UsernamePasswordAuthenticationToken) httpServletRequest.getUserPrincipal();
    String roleStr =  token.getAuthorities().iterator().next().getAuthority();
    String action = httpServletRequest.getServletPath();


    Role role = roleRepository.findOne(Long.parseLong(roleStr));

    if (role.getActions().contains(action)) {
        return true;
    }

    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}

The problem is that the response is always returning HTML, how to make the response return as JSON like the controllers annotated with @RestController ?

Thanks

like image 330
Dany Y Avatar asked Jan 13 '16 13:01

Dany Y


People also ask

How do you intercept a response in Spring boot?

To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.

What is HandlerInterceptorAdapter in Spring?

HandlerInterceptorAdapter is abstract adapter class for the HandlerInterceptor interface, for simplified implementation of pre-only/post-only interceptors.

What is ClientHttpRequestInterceptor?

Interface ClientHttpRequestInterceptor This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface ClientHttpRequestInterceptor. Intercepts client-side HTTP requests.

What is difference between interceptor and filter in Spring?

Filters can modify inbound and outbound requests and responses including modification of headers, entity and other request/response parameters. Interceptors are used primarily for modification of entity input and output streams. You can use interceptors for example to zip and unzip output and input entity streams.


1 Answers

package com.sha.home;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sha.model.Message;

public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{

    private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler)
        throws Exception {

        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
  System.out.println("start time"+startTime);

  ObjectMapper mapper = new ObjectMapper();
  Message msg = new Message("invalid","userinvalid");// customised pojo for error json message
  response.setContentType("application/json");
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  response.getWriter().write(mapper.writeValueAsString(msg));

  return false;


    }

    //after the handler is executed
    public void postHandle(
        HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView)
        throws Exception {

        long startTime = (Long)request.getAttribute("startTime");

        long endTime = System.currentTimeMillis();

        long executeTime = endTime - startTime;

        //modified the exisitng modelAndView


        //log it
        if(logger.isDebugEnabled()){
           logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
        }
    }
}

    enter code here
like image 186
sharath Avatar answered Nov 03 '22 16:11

sharath