Search in sources :

Example 6 with Header

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));
}
Also used : Header(com.predic8.membrane.core.http.Header) Request(com.predic8.membrane.core.http.Request)

Example 7 with Header

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);
    }
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Request(com.predic8.membrane.core.http.Request) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 8 with Header

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());
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) CacheBuilder(com.google.common.cache.CacheBuilder)

Example 9 with Header

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);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) DateTime(org.joda.time.DateTime)

Example 10 with Header

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;
}
Also used : Header(com.predic8.membrane.core.http.Header)

Aggregations

Exchange (com.predic8.membrane.core.exchange.Exchange)26 Header (com.predic8.membrane.core.http.Header)16 Request (com.predic8.membrane.core.http.Request)13 IOException (java.io.IOException)13 Response (com.predic8.membrane.core.http.Response)12 CacheBuilder (com.google.common.cache.CacheBuilder)8 Test (org.junit.Test)8 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)7 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)6 UnknownHostException (java.net.UnknownHostException)6 MCElement (com.predic8.membrane.annot.MCElement)5 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)4 AbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.AbstractExchangeSnapshot)4 DynamicAbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.DynamicAbstractExchangeSnapshot)4 HeaderField (com.predic8.membrane.core.http.HeaderField)4 JsonFactory (com.fasterxml.jackson.core.JsonFactory)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Cache (com.google.common.cache.Cache)2