use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.
the class RuleMatchingInterceptor method insertXForwardedFor.
private void insertXForwardedFor(AbstractExchange exc) {
Header h = exc.getRequest().getHeader();
if (h.getNumberOf(Header.X_FORWARDED_FOR) > maxXForwardedForHeaders) {
Request r = exc.getRequest();
throw new RuntimeException("Request caused " + Header.X_FORWARDED_FOR + " flood: " + r.getStartLine() + r.getHeader().toString());
}
h.setXForwardedFor(getXForwardedForHeaderValue(exc));
if (h.getNumberOf(Header.X_FORWARDED_PROTO) > maxXForwardedForHeaders) {
Request r = exc.getRequest();
throw new RuntimeException("Request caused " + Header.X_FORWARDED_PROTO + " flood: " + r.getStartLine() + r.getHeader().toString());
}
h.setXForwardedProto(getXForwardedProtoHeaderValue(exc));
if (h.getNumberOf(Header.X_FORWARDED_HOST) > maxXForwardedForHeaders) {
Request r = exc.getRequest();
throw new RuntimeException("Request caused " + Header.X_FORWARDED_HOST + " flood: " + r.getStartLine() + r.getHeader().toString());
}
h.setXForwardedHost(getXForwardedHostHeaderValue(exc));
}
use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.
the class OAuth2ResourceInterceptor method handleLoginRequest.
public void handleLoginRequest(Exchange exc) throws Exception {
Session s = sessionManager.getSession(exc);
String uri = exc.getRequest().getUri().substring(loginPath.length() - 1);
if (uri.indexOf('?') >= 0)
uri = uri.substring(0, uri.indexOf('?'));
exc.getDestinations().set(0, uri);
if (uri.equals("/logout")) {
if (s != null && s.getUserAttributes() != null) {
String token;
synchronized (s) {
token = s.getUserAttributes().get("access_token");
}
Exchange e = new Request.Builder().post(auth.getRevocationEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.USER_AGENT, Constants.USERAGENT).body(// TODO maybe send client credentials ( as it was before ) but Google doesn't accept that
"token=" + token).buildExchange();
Response response = auth.doRequest(e);
if (response.getStatusCode() != 200)
throw new RuntimeException("Revocation of token did not work. Statuscode: " + response.getStatusCode() + ".");
s.clear();
sessionManager.removeSession(exc);
}
exc.setResponse(Response.redirect("/", false).build());
} else if (uri.equals("/")) {
if (s == null || !s.isAuthorized()) {
String state = new BigInteger(130, new SecureRandom()).toString(32);
showPage(exc, state);
Session session = sessionManager.createSession(exc);
HashMap<String, String> userAttributes = new HashMap<String, String>();
userAttributes.put("state", state);
session.preAuthorize("", userAttributes);
} else {
showPage(exc, s.getUserAttributes().get("state"));
}
} else {
wsi.handleRequest(exc);
}
}
use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.
the class OAuth2ResourceInterceptor method refreshAccessToken.
private void refreshAccessToken(Session session) throws Exception {
if (!refreshingOfAccessTokenIsNeeded(session))
return;
OAuth2AnswerParameters oauth2Params = OAuth2AnswerParameters.deserialize(session.getUserAttributes().get(OAUTH2_ANSWER));
Exchange refreshTokenExchange = new Request.Builder().post(auth.getTokenEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.ACCEPT, "application/json").header(Header.USER_AGENT, Constants.USERAGENT).body("&grant_type=refresh_token" + "&refresh_token=" + oauth2Params.getRefreshToken()).buildExchange();
Response refreshTokenResponse = auth.doRequest(refreshTokenExchange);
if (!refreshTokenResponse.isOk()) {
refreshTokenResponse.getBody().read();
throw new RuntimeException("Statuscode from authorization server for refresh token request: " + refreshTokenResponse.getStatusCode());
}
HashMap<String, String> json = Util.parseSimpleJSONResponse(refreshTokenResponse);
if (json.get("access_token") == null || json.get("refresh_token") == null) {
refreshTokenResponse.getBody().read();
throw new RuntimeException("Statuscode was ok but no access_token and refresh_token was received: " + refreshTokenResponse.getStatusCode());
}
oauth2Params.setAccessToken(json.get("access_token"));
oauth2Params.setRefreshToken(json.get("refresh_token"));
oauth2Params.setExpiration(json.get("expires_in"));
oauth2Params.setReceivedAt(LocalDateTime.now());
if (json.containsKey("id_token")) {
if (idTokenIsValid(json.get("id_token")))
oauth2Params.setIdToken(json.get("id_token"));
else
oauth2Params.setIdToken("INVALID");
}
session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Params.serialize());
}
use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.
the class RateLimitInterceptor method setResponseToServiceUnavailable.
public void setResponseToServiceUnavailable(Exchange exc) throws UnsupportedEncodingException {
Header hd = new Header();
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US);
hd.add("Date", dateFormatter.print(DateTime.now()));
hd.add("X-LimitDuration", PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod()));
hd.add("X-LimitRequests", Integer.toString(rateLimitStrategy.requestLimit));
String ip = exc.getRemoteAddrIp();
DateTime availableAgainDateTime = rateLimitStrategy.getServiceAvailableAgainTime(ip);
hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));
StringBuilder bodyString = new StringBuilder();
DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
bodyString.append(ip).append(" exceeded the rate limit of ").append(rateLimitStrategy.requestLimit).append(" requests per ").append(PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod())).append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));
Response resp = ResponseBuilder.newInstance().status(429, "Too Many Requests.").contentType(MimeType.TEXT_PLAIN_UTF8).header(hd).body(bodyString.toString()).build();
exc.setResponse(resp);
}
use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.
the class REST2SOAPInterceptor method handleResponse.
@Override
public Outcome handleResponse(Exchange exc) throws Exception {
Mapping mapping = getRESTURL(exc);
log.debug("restURL: " + mapping);
if (getRESTURL(exc) == null)
return Outcome.CONTINUE;
if (log.isDebugEnabled())
log.debug("response: " + new String(getTransformer(null).transform(getBodySource(exc), exc.getStringProperties()), Constants.UTF_8_CHARSET));
exc.getResponse().setBodyContent(getTransformer(mapping.responseXSLT).transform(getBodySource(exc)));
Header header = exc.getResponse().getHeader();
header.removeFields(Header.CONTENT_TYPE);
header.setContentType(MimeType.TEXT_XML_UTF8);
XML2HTTP.unwrapMessageIfNecessary(exc.getResponse());
convertResponseToJSONIfNecessary(exc.getRequest().getHeader(), mapping, exc.getResponse(), exc.getStringProperties());
return Outcome.CONTINUE;
}
Aggregations