Search in sources :

Example 56 with Response

use of com.predic8.membrane.core.http.Response 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 57 with Response

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

the class OAuth2ResourceInterceptor method revalidateToken.

private HashMap<String, String> revalidateToken(OAuth2AnswerParameters params) throws Exception {
    Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", params.getTokenType() + " " + params.getAccessToken()).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
    Response response2 = auth.doRequest(e2);
    if (response2.getStatusCode() != 200) {
        statistics.accessTokenInvalid();
        return null;
    } else {
        statistics.accessTokenValid();
        return Util.parseSimpleJSONResponse(response2);
    }
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) Request(com.predic8.membrane.core.http.Request)

Example 58 with Response

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

the class AMStatisticsCollector method sendJsonToElasticSearch.

private void sendJsonToElasticSearch(String path, String json) throws Exception {
    Response resp = null;
    synchronized (client) {
        Exchange exc = new Request.Builder().put(getElasticSearchPath(path)).body(json).buildExchange();
        if (clientId != null && clientSecret != null)
            exc.getRequest().getHeader().add(Header.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes("UTF-8")), "UTF-8"));
        resp = client.call(exc).getResponse();
    }
    if (!resp.isOk())
        log.warn("Could not send statistics to elastic search instance. Response: " + resp.getStatusCode() + " - " + resp.getStatusMessage() + " - " + resp.getBodyAsStringDecoded());
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange)

Example 59 with Response

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

the class ApiManagementInterceptor method setErrorResponse.

private void setErrorResponse(Exchange exc, Response.ResponseBuilder builder) {
    Response res = builder.contentType(APPLICATION_JSON).build();
    res.setBodyContent(buildJsonErrorMessage(res));
    exc.setResponse(res);
}
Also used : Response(com.predic8.membrane.core.http.Response)

Example 60 with Response

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

the class OAuth2ApiTest method test.

@Test
public void test() throws Exception {
    Process2 sl = new Process2.Builder().in(getExampleDir("oauth2/api/authorization_server")).script("service-proxy").waitForMembrane().start();
    Process2 sl2 = new Process2.Builder().in(getExampleDir("oauth2/api/token_validator")).script("service-proxy").waitForMembrane().start();
    BufferLogger b = new BufferLogger();
    Process2 sl3 = new Process2.Builder().in(getExampleDir("oauth2/api")).withWatcher(b).script("start").waitAfterStartFor("OK").start();
    // sl3 can fail because at least the start.sh is very fragile in parsing the response for the access token. If the number or order of the params changes then start.sh will fail.
    try {
        // This is kind of redundant as sl3 already waits until "OK" is written or timeouts when its not
        assertTrue(b.toString().contains("OK"));
    } finally {
        sl.killScript();
        sl2.killScript();
        sl3.killScript();
    }
}
Also used : Process2(com.predic8.membrane.examples.Process2) BufferLogger(com.predic8.membrane.examples.util.BufferLogger) Test(org.junit.Test)

Aggregations

Response (com.predic8.membrane.core.http.Response)29 Exchange (com.predic8.membrane.core.exchange.Exchange)14 IOException (java.io.IOException)14 StringWriter (java.io.StringWriter)9 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)7 Request (com.predic8.membrane.core.http.Request)7 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)6 Header (com.predic8.membrane.core.http.Header)6 Test (org.junit.Test)6 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)4 Message (com.predic8.membrane.core.http.Message)4 JSONContent (com.predic8.membrane.core.interceptor.rest.JSONContent)4 ProxyRule (com.predic8.membrane.core.rules.ProxyRule)4 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)4 SQLException (java.sql.SQLException)4 Element (org.w3c.dom.Element)4 NodeList (org.w3c.dom.NodeList)4 JsonFactory (com.fasterxml.jackson.core.JsonFactory)3 MCElement (com.predic8.membrane.annot.MCElement)3 ResponseBuilder (com.predic8.membrane.core.http.Response.ResponseBuilder)3