Search in sources :

Example 11 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class RevocationEndpointProcessor method process.

@Override
public Outcome process(Exchange exc) throws Exception {
    Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
    if (!params.containsKey("token")) {
        exc.setResponse(OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "invalid_request"));
        return Outcome.RETURN;
    }
    SessionManager.Session session = authServer.getSessionFinder().getSessionForToken(params.get("token"));
    if (session == null) {
        // token doesnt exist -> token is already invalid
        exc.setResponse(Response.ok().bodyEmpty().build());
        return Outcome.RETURN;
    }
    Client client;
    Map<String, String> userAttributes = session.getUserAttributes();
    synchronized (userAttributes) {
        try {
            client = authServer.getClientList().getClient(userAttributes.get(ParamNames.CLIENT_ID));
        } catch (Exception e) {
            // This should never happen
            exc.setResponse(Response.ok().bodyEmpty().build());
            return Outcome.RETURN;
        }
    }
    String paramClientId = params.get(ParamNames.CLIENT_ID);
    String paramClientSecret = params.get(ParamNames.CLIENT_SECRET);
    if ((paramClientId != null && !client.getClientId().equals(paramClientId)) || (paramClientSecret != null && !client.getClientSecret().equals(paramClientSecret))) {
        exc.setResponse(OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "invalid_grant"));
        return Outcome.RETURN;
    }
    try {
        authServer.getTokenGenerator().invalidateToken(params.get("token"), client.getClientId(), client.getClientSecret());
    } catch (Exception e) {
        exc.setResponse(OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "invalid_grant"));
        return Outcome.RETURN;
    }
    synchronized (session) {
        session.clear();
    }
    synchronized (authServer.getSessionManager()) {
        authServer.getSessionManager().removeSession(session);
    }
    synchronized (authServer.getSessionFinder()) {
        authServer.getSessionFinder().removeSessionForToken(params.get("token"));
    }
    exc.setResponse(Response.ok().bodyEmpty().build());
    return Outcome.RETURN;
}
Also used : SessionManager(com.predic8.membrane.core.interceptor.authentication.session.SessionManager) Client(com.predic8.membrane.core.interceptor.oauth2.Client)

Example 12 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class ClusterBalancerTest method testClusterBalancerRequest.

@Test
public void testClusterBalancerRequest() throws Exception {
    Exchange exc = getExchangeWithSession();
    lb.handleRequest(exc);
    Session s = BalancerUtil.getSessions(r, "Default", "Default").get("555555");
    assertEquals("localhost", s.getNode().getHost());
    assertEquals(2, exc.getDestinations().size());
    String stickyDestination = exc.getDestinations().get(0);
    lb.handleRequest(exc);
    assertEquals(1, BalancerUtil.getSessions(r, "Default", "Default").size());
    assertEquals(stickyDestination, exc.getDestinations().get(0));
    BalancerUtil.takeout(r, "Default", "Default", "localhost", s.getNode().getPort());
    assertEquals(1, BalancerUtil.getAvailableNodesByCluster(r, "Default", "Default").size());
    assertFalse(stickyDestination.equals(BalancerUtil.getAvailableNodesByCluster(r, "Default", "Default").get(0)));
    lb.handleRequest(exc);
    assertEquals(stickyDestination, exc.getDestinations().get(0));
    BalancerUtil.down(r, "Default", "Default", "localhost", s.getNode().getPort());
    lb.handleRequest(exc);
    assertFalse(stickyDestination.equals(exc.getDestinations().get(0)));
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange)

Example 13 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class ClusterBalancerTest method setUp.

@Override
@Before
public void setUp() throws Exception {
    extracor = new XMLElementSessionIdExtractor();
    extracor.setLocalName("session");
    extracor.setNamespace("http://predic8.com/session/");
    r = new HttpRouter();
    lb = new LoadBalancingInterceptor();
    lb.setSessionIdExtractor(extracor);
    lb.setName("Default");
    ServiceProxy sp = new ServiceProxy(new ServiceProxyKey(3011), "predic8.com", 80);
    sp.getInterceptors().add(lb);
    r.getRuleManager().addProxyAndOpenPortIfNew(sp);
    r.init();
    BalancerUtil.up(r, "Default", "Default", "localhost", 2000);
    BalancerUtil.up(r, "Default", "Default", "localhost", 3000);
}
Also used : ServiceProxyKey(com.predic8.membrane.core.rules.ServiceProxyKey) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy)

Example 14 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class LoadBalancingWithClusterManagerTest method startLB.

private void startLB() throws Exception {
    LoadBalancingInterceptor lbi = new LoadBalancingInterceptor();
    lbi.setName("Default");
    XMLElementSessionIdExtractor extractor = new XMLElementSessionIdExtractor();
    extractor.setLocalName("session");
    extractor.setNamespace("http://predic8.com/session/");
    lbi.setSessionIdExtractor(extractor);
    ServiceProxy lbiRule = new ServiceProxy(new ServiceProxyKey("localhost", "*", ".*", 3017), "thomas-bayer.com", 80);
    lbiRule.getInterceptors().add(lbi);
    ClusterNotificationInterceptor cni = new ClusterNotificationInterceptor();
    ServiceProxy cniRule = new ServiceProxy(new ServiceProxyKey("localhost", "*", ".*", 3012), "thomas-bayer.com", 80);
    cniRule.getInterceptors().add(cni);
    lb = new HttpRouter();
    lb.getRuleManager().addProxyAndOpenPortIfNew(lbiRule);
    lb.getRuleManager().addProxyAndOpenPortIfNew(cniRule);
    lb.init();
}
Also used : ServiceProxyKey(com.predic8.membrane.core.rules.ServiceProxyKey) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) HttpRouter(com.predic8.membrane.core.HttpRouter)

Example 15 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session 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)

Aggregations

Session (com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)5 Exchange (com.predic8.membrane.core.exchange.Exchange)4 Response (com.predic8.membrane.core.http.Response)3 ParseException (com.floreysoft.jmte.message.ParseException)2 CacheBuilder (com.google.common.cache.CacheBuilder)2 Request (com.predic8.membrane.core.http.Request)2 SessionManager (com.predic8.membrane.core.interceptor.authentication.session.SessionManager)2 Client (com.predic8.membrane.core.interceptor.oauth2.Client)2 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)2 ServiceProxyKey (com.predic8.membrane.core.rules.ServiceProxyKey)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 BigInteger (java.math.BigInteger)2 MalformedURLException (java.net.MalformedURLException)2 SecureRandom (java.security.SecureRandom)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 HttpRouter (com.predic8.membrane.core.HttpRouter)1 LogInterceptor (com.predic8.membrane.core.interceptor.LogInterceptor)1 Session (com.predic8.membrane.core.interceptor.balancer.Session)1