這是本文件的舊版!


Incorrect response(401) when using X-HTTP-Method-Override

我們使用Spring的Rest,先前為了支援X-HTTP-Method-Override,在已存在的Filter做了此功能。某天,同事發現使用apache client api操作我們的API發生了401錯誤。而要發生這個問題有兩個條件,

  1. 使用Digest認證
  2. 使用X-HTTP-Method-Override

因此在我有空時,就開始追蹤這問題。

Sprint Security提供了DigestAuthentationFilter負責處理Digest認證。在使用者發出第一次請求後,Spring Security在察覺未經過驗證的情況下,會透過AuthenticationEntryPoint送出請求認證資訊。為了在認證失敗時,能夠輸出xml或json格式的錯誤訊息,

		
{"code":401,"message":"Incorrect response","links":[{"rel":"more info","href":"http://192.168.1.110:8080/TestWeb/api/documents"}]}
我們extend了DigestAuthenticationEntryPoint:
public class JsonDigestAuthenticationEntryPoint extends DigestAuthenticationEntryPoint {
 
	private static final Log logger = LogFactory.getLog(JsonDigestAuthenticationEntryPoint.class);
 
	@Autowired
	private MessageProcessor mMessageProcessor;
 
	@Override
	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
 
		// ... skip
 
		httpResponse.addHeader("WWW-Authenticate", authenticateHeader);
 
		try {
			ErrorInfo erroInfo = ErrorResponseEntityCreator.createErrorInfo(request, HttpStatus.UNAUTHORIZED.value(),
					authException.getMessage());
 
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			mMessageProcessor.handle(erroInfo, request, response);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}
 
}