Search in sources :

Example 1 with Response

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

the class Response method parseStartLine.

@Override
public void parseStartLine(InputStream in) throws IOException, EndOfStreamException {
    String line;
    try {
        line = HttpUtil.readLine(in);
    } catch (EOFWhileReadingLineException e) {
        if (e.getLineSoFar().length() == 0)
            throw new NoResponseException(e);
        throw new EOFWhileReadingFirstLineException(e.getLineSoFar());
    }
    Matcher matcher = pattern.matcher(line);
    boolean find = matcher.find();
    if (!find) {
        throw new RuntimeException("Invalid server response: " + line);
    }
    version = matcher.group(1);
    statusCode = Integer.parseInt(matcher.group(2));
    statusMessage = matcher.group(4);
}
Also used : Matcher(java.util.regex.Matcher) EOFWhileReadingFirstLineException(com.predic8.membrane.core.transport.http.EOFWhileReadingFirstLineException) NoResponseException(com.predic8.membrane.core.transport.http.NoResponseException) EOFWhileReadingLineException(com.predic8.membrane.core.transport.http.EOFWhileReadingLineException)

Example 2 with Response

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

the class LimitedMemoryExchangeStore method oldSnap.

private void oldSnap(AbstractExchange exc, Flow flow) {
    // TODO: [fix me] support multi-snap
    // TODO: [fix me] snap message headers and request *here*, not in observer/response
    exc.addExchangeViewerListener(new AbstractExchangeViewerListener() {

        @Override
        public void setExchangeFinished() {
            inflight.remove(exc);
        }
    });
    if (flow == Flow.REQUEST) {
        exc.getRequest().addObserver(new MessageObserver() {

            @Override
            public void bodyRequested(AbstractBody body) {
            }

            @Override
            public void bodyComplete(AbstractBody body) {
                Response r = exc.getResponse();
                if (r != null) {
                    AbstractBody b = r.getBody();
                    if (b != null && b.isRead())
                        // request-bodyComplete might occur after response-bodyComplete
                        return;
                }
                // System.out.println("Exchange put inflight " + exc.hashCode() + " " + exc.getRequest().getStartLine());
                inflight.put(exc, exc.getRequest());
                modify();
            }
        });
        return;
    }
    try {
        Message m = exc.getResponse();
        if (m != null)
            m.addObserver(new MessageObserver() {

                public void bodyRequested(AbstractBody body) {
                }

                public void bodyComplete(AbstractBody body) {
                    snapInternal(exc, flow);
                    inflight.remove(exc);
                    modify();
                // System.out.println("Exchange remove inflight " + exc.hashCode());
                }
            });
        else {
            inflight.remove(exc);
            modify();
        // System.out.println("Exchange remove inflight " + exc.hashCode() + " (2)");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : AbstractExchangeViewerListener(com.predic8.membrane.core.model.AbstractExchangeViewerListener)

Example 3 with Response

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

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

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

the class AuthWithoutSessionRequest method processWithParameters.

@Override
protected Response processWithParameters() throws Exception {
    Client client;
    try {
        client = authServer.getClientList().getClient(getClientId());
    } catch (Exception e) {
        return OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "unauthorized_client");
    }
    if (!OAuth2Util.isAbsoluteUri(getRedirectUri()) || !getRedirectUri().equals(client.getCallbackUrl()))
        return OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "invalid_request");
    if (promptEqualsNone())
        return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=login_required");
    if (!authServer.getSupportedAuthorizationGrants().contains(getResponseType()))
        return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=unsupported_response_type");
    String validScopes = verifyScopes(getScope());
    if (validScopes.isEmpty())
        return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=invalid_scope");
    if (OAuth2Util.isOpenIdScope(validScopes)) {
        if (!isCodeRequest())
            return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=invalid_request");
        // Parses the claims parameter into a json object. Claim values are always ignored and set to "null" as it is optional to react to those values
        addValidClaimsToParams();
    } else
        removeClaimsWhenNotOpenidScope();
    setScope(validScopes);
    String invalidScopes = hasGivenInvalidScopes(getScope(), validScopes);
    if (!invalidScopes.isEmpty())
        setScopeInvalid(invalidScopes);
    SessionManager.Session session = authServer.getSessionManager().getOrCreateSession(exc);
    addParams(session, params);
    return new NoResponse();
}
Also used : SessionManager(com.predic8.membrane.core.interceptor.authentication.session.SessionManager) Client(com.predic8.membrane.core.interceptor.oauth2.Client) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

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