@Override
	public void doFilter(ServletRequest sreq, ServletResponse sresp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) sreq;
		HttpServletResponse resp = (HttpServletResponse) sresp;
		OAuthMessage m = new OAuthMessage(req);
		String fakescheme = req.getHeader("X-OauthProxy-Scheme");
		String fakeport = req.getHeader("X-OauthProxy-Port");
		if (fakescheme != null)
			m.setScheme(fakescheme);
		if (fakeport != null)
			m.setPort(Integer.parseInt(fakeport.trim()));

		if (m.getSignature() != null) {
			String consumer = m.getConsumerKey();
			if (consumer == null) {
				resp.sendError(401, "No Consumer Key");
				return;
			}
			String token = m.getToken();
			OAuthConsumer c;
			OAuthUser u;
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				c = pm.getObjectById(OAuthConsumer.class, consumer);
				if (!c.getMethod().equals(m.getSignatureMethod())) {
					resp.sendError(401, "Sign method mismatch");
					return;
				}
				if (token != null) {
					// token is null when requesting token
					u = pm.getObjectById(OAuthUser.class, token);
				} else {
					u = new OAuthUser(null, null);
				}
			} catch (javax.jdo.JDOObjectNotFoundException e) {
				resp.sendError(401, e.getLocalizedMessage());
				return;
			} finally {
				pm.close();
			}

			try {
				new SimpleOAuthValidator().validateMessage(m, c, u);
			} catch (OAuthException e) {
				resp.sendError(401, e.getLocalizedMessage());
				return;
			} catch (URISyntaxException e) {
				resp.sendError(500, e.getLocalizedMessage());
				return;
			}
		}
		chain.doFilter(req, resp);
	}