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
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.
HandlerInterceptorAdapter is abstract adapter class for the HandlerInterceptor interface, for simplified implementation of pre-only/post-only interceptors.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With