2016-01-13 98 views
0

我有一個REST Webservice的spring引導應用程序。Spring引導攔截器返回JSON

我想添加一個攔截器,以便每個沒有特定操作權限的角色返回401錯誤代碼。

@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; 
} 

的問題是,響應總是返回HTML,如何做出反應回報JSON像@RestController註釋的控制器?

感謝

+0

您正在使用Spring Security的,那麼爲什麼在地球上玉需要這個? Spring Security已經爲你做了這個... –

+0

我想動態地修改動作,並且這些動作可能不僅與他們可以在函數內部調節的url有關,這是否可以在spring security中執行? –

+0

您是否閱讀過文檔?您可以使用基於URL和/或方法的安全性,它們對於表達式和全部也可能非常複雜。 –

回答

1
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 
+0

請添加爲何此代碼回答此問題。沒有任何解釋,這個大小的代碼塊並不是有效的答案。 – trincot