Search in sources :

Example 61 with Request

use of com.predic8.membrane.core.http.Request in project service-proxy by membrane.

the class MessageUtil method getPostRequest.

public static Request getPostRequest(String uri) {
    Request req = getStandartRequest(Request.METHOD_POST);
    req.setUri(uri);
    return req;
}
Also used : Request(com.predic8.membrane.core.http.Request)

Example 62 with Request

use of com.predic8.membrane.core.http.Request in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method handleRequest.

public boolean handleRequest(Exchange exc, String state, String publicURL, Session session) throws Exception {
    String path = uriFactory.create(exc.getDestinations().get(0)).getPath();
    if (path == null)
        return false;
    if (path.endsWith("/oauth2callback")) {
        try {
            Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
            String state2 = params.get("state");
            if (state2 == null)
                throw new RuntimeException("No CSRF token.");
            Map<String, String> param = URLParamUtil.parseQueryString(state2);
            if (param == null || !param.containsKey("security_token"))
                throw new RuntimeException("No CSRF token.");
            boolean csrfMatch = false;
            for (String state3 : stateToOriginalUrl.keySet()) if (param.get("security_token").equals(state3))
                csrfMatch = true;
            if (!csrfMatch)
                throw new RuntimeException("CSRF token mismatch.");
            Request originalRequest = stateToOriginalUrl.get(param.get("security_token"));
            String url = originalRequest.getUri();
            if (url == null)
                url = "/";
            stateToOriginalUrl.remove(state2);
            if (log.isDebugEnabled())
                log.debug("CSRF token match.");
            String code = params.get("code");
            if (code == null)
                throw new RuntimeException("No code received.");
            Exchange e = 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("code=" + code + "&client_id=" + auth.getClientId() + "&client_secret=" + auth.getClientSecret() + "&redirect_uri=" + publicURL + "oauth2callback" + "&grant_type=authorization_code").buildExchange();
            LogInterceptor logi = null;
            if (log.isDebugEnabled()) {
                logi = new LogInterceptor();
                logi.setHeaderOnly(false);
                logi.handleRequest(e);
            }
            Response response = auth.doRequest(e);
            if (response.getStatusCode() != 200) {
                response.getBody().read();
                throw new RuntimeException("Authentication server returned " + response.getStatusCode() + ".");
            }
            if (log.isDebugEnabled())
                logi.handleResponse(e);
            HashMap<String, String> json = Util.parseSimpleJSONResponse(response);
            if (!json.containsKey("access_token"))
                throw new RuntimeException("No access_token received.");
            // and also "scope": "", "token_type": "bearer"
            String token = (String) json.get("access_token");
            OAuth2AnswerParameters oauth2Answer = new OAuth2AnswerParameters();
            synchronized (session) {
                // saving for logout
                session.getUserAttributes().put("access_token", token);
            }
            oauth2Answer.setAccessToken(token);
            oauth2Answer.setTokenType(json.get("token_type"));
            oauth2Answer.setExpiration(json.get("expires_in"));
            oauth2Answer.setRefreshToken(json.get("refresh_token"));
            oauth2Answer.setReceivedAt(LocalDateTime.now());
            if (json.containsKey("id_token")) {
                if (idTokenIsValid(json.get("id_token")))
                    oauth2Answer.setIdToken(json.get("id_token"));
                else
                    oauth2Answer.setIdToken("INVALID");
            }
            validTokens.put(token, true);
            Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", json.get("token_type") + " " + token).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
            if (log.isDebugEnabled()) {
                logi.setHeaderOnly(false);
                logi.handleRequest(e2);
            }
            Response response2 = auth.doRequest(e2);
            if (log.isDebugEnabled())
                logi.handleResponse(e2);
            if (response2.getStatusCode() != 200) {
                statistics.accessTokenInvalid();
                throw new RuntimeException("User data could not be retrieved.");
            }
            statistics.accessTokenValid();
            HashMap<String, String> json2 = Util.parseSimpleJSONResponse(response2);
            oauth2Answer.setUserinfo(json2);
            session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Answer.serialize());
            processUserInfo(json2, session);
            exc.setRequest(originalRequest);
            return true;
        } catch (Exception e) {
            exc.setResponse(Response.badRequest().body(e.getMessage()).build());
            return true;
        }
    }
    return false;
}
Also used : CacheBuilder(com.google.common.cache.CacheBuilder) Request(com.predic8.membrane.core.http.Request) ParseException(com.floreysoft.jmte.message.ParseException) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) LogInterceptor(com.predic8.membrane.core.interceptor.LogInterceptor)

Example 63 with Request

use of com.predic8.membrane.core.http.Request in project service-proxy by membrane.

the class RequestInterceptor method handleRequest.

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    boolean logDebug = log.isDebugEnabled();
    for (Interceptor i : getInterceptors()) {
        EnumSet<Flow> f = i.getFlow();
        if (!f.contains(Flow.REQUEST))
            continue;
        if (logDebug)
            log.debug("Invoking request handler: " + i.getDisplayName() + " on exchange: " + exc);
        Outcome o = i.handleRequest(exc);
        if (o != Outcome.CONTINUE)
            return o;
    }
    return Outcome.CONTINUE;
}
Also used : Outcome(com.predic8.membrane.core.interceptor.Outcome) Interceptor(com.predic8.membrane.core.interceptor.Interceptor)

Example 64 with Request

use of com.predic8.membrane.core.http.Request in project service-proxy by membrane.

the class HttpServerHandler method process.

private void process() throws Exception {
    try {
        DNSCache dnsCache = getTransport().getRouter().getDnsCache();
        InetAddress remoteAddr = sourceSocket.getInetAddress();
        String ip = dnsCache.getHostAddress(remoteAddr);
        exchange.setRemoteAddrIp(ip);
        exchange.setRemoteAddr(getTransport().isReverseDNS() ? dnsCache.getHostName(remoteAddr) : ip);
        exchange.setRequest(srcReq);
        exchange.setOriginalRequestUri(srcReq.getUri());
        if (exchange.getRequest().getHeader().is100ContinueExpected()) {
            final Request request = exchange.getRequest();
            request.addObserver(new MessageObserver() {

                public void bodyRequested(AbstractBody body) {
                    try {
                        if (request.getHeader().is100ContinueExpected()) {
                            // request body from client so that interceptors can handle it
                            Response.continue100().build().write(srcOut);
                            // remove "Expect: 100-continue" since we already sent "100 Continue"
                            request.getHeader().removeFields(Header.EXPECT);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

                public void bodyComplete(AbstractBody body) {
                }
            });
        }
        invokeHandlers();
        exchange.blockResponseIfNeeded();
    } catch (AbortException e) {
        log.debug("Aborted");
        exchange.finishExchange(true, e.getMessage());
        removeBodyFromBuffer();
        writeResponse(exchange.getResponse());
        log.debug("exchange set aborted");
        return;
    }
    try {
        removeBodyFromBuffer();
        writeResponse(exchange.getResponse());
        exchange.setCompleted();
        log.debug("exchange set completed");
    } catch (Exception e) {
        exchange.finishExchange(true, e.getMessage());
        throw e;
    }
}
Also used : MessageObserver(com.predic8.membrane.core.http.MessageObserver) Request(com.predic8.membrane.core.http.Request) AbstractBody(com.predic8.membrane.core.http.AbstractBody) DNSCache(com.predic8.membrane.core.util.DNSCache) InetAddress(java.net.InetAddress) IOException(java.io.IOException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) SocketException(java.net.SocketException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 65 with Request

use of com.predic8.membrane.core.http.Request in project service-proxy by membrane.

the class HttpServerHandler method run.

public void run() {
    // see Request.isBindTargetConnectionToIncoming()
    Connection boundConnection = null;
    try {
        updateThreadName(true);
        setup();
        while (true) {
            srcReq = new Request();
            endpointListener.setIdleStatus(sourceSocket, true);
            try {
                srcIn.mark(2);
                if (srcIn.read() == -1)
                    break;
                srcIn.reset();
            } finally {
                endpointListener.setIdleStatus(sourceSocket, false);
            }
            if (boundConnection != null) {
                exchange.setTargetConnection(boundConnection);
                boundConnection = null;
            }
            srcReq.read(srcIn, true);
            exchange.received();
            if (srcReq.getHeader().getProxyConnection() != null) {
                srcReq.getHeader().add(Header.CONNECTION, srcReq.getHeader().getProxyConnection());
                srcReq.getHeader().removeFields(Header.PROXY_CONNECTION);
            }
            process();
            if (srcReq.isCONNECTRequest()) {
                log.debug("stopping HTTP Server Thread after establishing an HTTP connect");
                return;
            }
            boundConnection = exchange.getTargetConnection();
            exchange.setTargetConnection(null);
            if (!exchange.canKeepConnectionAlive())
                break;
            if (exchange.getResponse().isRedirect()) {
                break;
            }
            exchange.detach();
            exchange = new Exchange(this);
        }
    } catch (SocketTimeoutException e) {
        log.debug("Socket of thread " + counter + " timed out");
    } catch (SocketException se) {
        log.debug("client socket closed");
    } catch (SSLException s) {
        if (showSSLExceptions) {
            if (s.getCause() instanceof SSLException)
                s = (SSLException) s.getCause();
            if (s.getCause() instanceof SocketException)
                log.debug("ssl socket closed");
            else
                log.error("", s);
        }
    } catch (IOException e) {
        log.error("", e);
    } catch (EndOfStreamException e) {
        log.debug("stream closed");
    } catch (AbortException e) {
        log.debug("exchange aborted.");
    } catch (NoMoreRequestsException e) {
    // happens at the end of a keep-alive connection
    } catch (NoResponseException e) {
        log.debug("No response received. Maybe increase the keep-alive timeout on the server.");
    } catch (EOFWhileReadingFirstLineException e) {
        log.debug("Client connection terminated before line was read. Line so far: (" + e.getLineSoFar() + ")");
    } catch (Exception e) {
        log.error("", e);
    } finally {
        endpointListener.setOpenStatus(sourceSocket, false);
        if (boundConnection != null)
            try {
                boundConnection.close();
            } catch (IOException e) {
                log.debug("Closing bound connection.", e);
            }
        closeConnections();
        exchange.detach();
        updateThreadName(false);
    }
}
Also used : SocketException(java.net.SocketException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) Request(com.predic8.membrane.core.http.Request) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) IOException(java.io.IOException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) SocketException(java.net.SocketException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException) Exchange(com.predic8.membrane.core.exchange.Exchange) SocketTimeoutException(java.net.SocketTimeoutException)

Aggregations

Request (com.predic8.membrane.core.http.Request)39 Exchange (com.predic8.membrane.core.exchange.Exchange)20 Test (org.junit.Test)12 IOException (java.io.IOException)11 Header (com.predic8.membrane.core.http.Header)8 Response (com.predic8.membrane.core.http.Response)8 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)5 Message (com.predic8.membrane.core.http.Message)5 Outcome (com.predic8.membrane.core.interceptor.Outcome)5 Body (com.predic8.membrane.core.http.Body)3 Request (com.predic8.membrane.core.http.xml.Request)3 EndOfStreamException (com.predic8.membrane.core.util.EndOfStreamException)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 CacheBuilder (com.google.common.cache.CacheBuilder)2 HeaderField (com.predic8.membrane.core.http.HeaderField)2 ResponseBuilder (com.predic8.membrane.core.http.Response.ResponseBuilder)2 ResolverMap (com.predic8.membrane.core.resolver.ResolverMap)2 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)2 StringReader (java.io.StringReader)2 SocketException (java.net.SocketException)2