Search in sources :

Example 6 with Session

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

the class LoadBalancerSession3Test method test.

/**
 * The test as described in README.txt, but "wsimport" (previously called by ant)
 * was removed and is run directly from this test before everything else. Thereby
 * we can use a Maven dependency on wsimport and do not have to download it ourselves.
 */
@Test
public void test() throws IOException, InterruptedException {
    File base = getExampleDir("loadbalancer-session-3");
    AssertUtils.replaceInFile(new File(base, "proxies.xml"), "8080", "3023");
    AssertUtils.replaceInFile(new File(base, "src/com/predic8/chat/Client.java"), "8080", "3023");
    AssertUtils.replaceInFile(new File(base, "data/ChatService.wsdl"), "8080", "3023");
    Process2 sl = new Process2.Builder().in(base).script("service-proxy").waitForMembrane().start();
    try {
        File buildXML = new File(base, "build.xml");
        // remove <exec...</exec> from build.xml
        String s = Pattern.compile("<exec.*</exec>", Pattern.DOTALL).matcher(FileUtils.readFileToString(buildXML)).replaceAll("");
        FileUtils.writeStringToFile(buildXML, s);
        File classes = new File(base, "build" + File.separator + "classes");
        classes.mkdirs();
        File source = new File(base, "src");
        source.mkdirs();
        // run "wsimport" generating java sources
        Assert.assertTrue(new com.sun.tools.ws.wscompile.WsimportTool(System.out).run(new String[] { "-quiet", "-Xnocompile", new File(base, "data" + File.separator + "ChatService.wsdl").getAbsolutePath(), "-s", source.getAbsolutePath() }));
        // call "ant compile" now so that both antNodeX processes do call it at the same time
        BufferLogger loggerCompile = new BufferLogger();
        Process2 antCompile = new Process2.Builder().in(base).withWatcher(loggerCompile).executable("ant compile").start();
        try {
            int result = antCompile.waitFor(60000);
            if (result != 0)
                throw new AssertionError("'ant compile' returned non-zero " + result + ":\r\n" + loggerCompile.toString());
        } finally {
            antCompile.killScript();
        }
        BufferLogger loggerNode1 = new BufferLogger();
        BufferLogger loggerNode2 = new BufferLogger();
        Process2 antNode1 = new Process2.Builder().in(base).withWatcher(loggerNode1).executable("ant run-node1").start();
        try {
            Process2 antNode2 = new Process2.Builder().in(base).withWatcher(loggerNode2).executable("ant run-node2").start();
            try {
                LoadBalancerUtil.addLBNodeViaHTML("http://localhost:9000/admin/", "localhost", 4000);
                LoadBalancerUtil.addLBNodeViaHTML("http://localhost:9000/admin/", "localhost", 4001);
                // wait for nodes to come up
                Thread.sleep(1000);
                Process2 antClient = new Process2.Builder().in(base).executable("ant run-client -Dlogin=jim").start();
                try {
                    antClient.waitFor(60000);
                } finally {
                    antClient.killScript();
                }
            } finally {
                antNode2.killScript();
            }
        } finally {
            antNode1.killScript();
        }
        AssertUtils.assertContains("Hallo World", loggerNode1.toString());
        AssertUtils.assertContainsNot("Hallo World", loggerNode2.toString());
    } finally {
        sl.killScript();
    }
}
Also used : Process2(com.predic8.membrane.examples.Process2) BufferLogger(com.predic8.membrane.examples.util.BufferLogger) File(java.io.File) Test(org.junit.Test)

Example 7 with Session

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

the class AdminPageBuilder method createSessionsTable.

protected void createSessionsTable(List<Session> sessions) {
    table().attr("cellpadding", "0", "cellspacing", "0", "border", "0", "class", "display sessionsTable");
    thead();
    tr();
    createThs("Id", "Last Used");
    end();
    end();
    tbody();
    for (Session s : sessions) {
        tr();
        createTds(s.getId(), formatDurationHMS(System.currentTimeMillis() - s.getLastUsed()));
        end();
    }
    end();
    end();
}
Also used : Session(com.predic8.membrane.core.interceptor.balancer.Session)

Example 8 with Session

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

the class LoginDialog method handleLoginRequest.

public void handleLoginRequest(Exchange exc) throws Exception {
    Session s = sessionManager.getSession(exc);
    String uri = exc.getRequest().getUri().substring(path.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.clear();
        exc.setResponse(Response.redirect(path, false).body("").build());
    } else if (uri.equals("/consent")) {
        if (exc.getRequest().getMethod().equals("POST"))
            processConsentPageResult(exc, s);
        else
            showConsentPage(exc, s);
    } else if (uri.equals("/")) {
        if (s == null || !s.isPreAuthorized()) {
            if (exc.getRequest().getMethod().equals("POST")) {
                Map<String, String> userAttributes;
                Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
                String username = params.get("username");
                if (username == null) {
                    showPage(exc, 0, "error", "INVALID_PASSWORD");
                    return;
                }
                if (accountBlocker != null && accountBlocker.isBlocked(username)) {
                    showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
                    return;
                }
                try {
                    userAttributes = userDataProvider.verify(params);
                } catch (NoSuchElementException e) {
                    List<String> params2 = Lists.newArrayList("error", "INVALID_PASSWORD");
                    if (accountBlocker != null) {
                        if (accountBlocker.fail(username))
                            params2.addAll(Lists.newArrayList("accountBlocked", "true"));
                    }
                    showPage(exc, 0, params2.toArray());
                    return;
                } catch (Exception e) {
                    log.error("", e);
                    showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
                    return;
                }
                if (exposeUserCredentialsToSession) {
                    for (Map.Entry<String, String> param : params.entrySet()) if (!userAttributes.containsKey(param.getKey()))
                        userAttributes.put(param.getKey(), param.getValue());
                }
                if (tokenProvider != null)
                    showPage(exc, 1);
                else {
                    String target = params.get("target");
                    if (StringUtils.isEmpty(target))
                        target = "/";
                    exc.setResponse(Response.redirectWithout300(target).build());
                }
                Session session = sessionManager.getOrCreateSession(exc);
                session.preAuthorize(username, userAttributes);
                if (tokenProvider != null)
                    tokenProvider.requestToken(session.getUserAttributes());
            } else {
                showPage(exc, 0);
            }
        } else {
            if (accountBlocker != null && accountBlocker.isBlocked(s.getUserName())) {
                showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
                return;
            }
            if (exc.getRequest().getMethod().equals("POST")) {
                String token = URLParamUtil.getParams(uriFactory, exc).get("token");
                try {
                    if (tokenProvider != null)
                        tokenProvider.verifyToken(s.getUserAttributes(), token);
                } catch (NoSuchElementException e) {
                    List<String> params = Lists.newArrayList("error", "INVALID_TOKEN");
                    if (accountBlocker != null)
                        if (accountBlocker.fail(s.getUserName()))
                            params.addAll(Lists.newArrayList("accountBlocked", "true"));
                    s.clear();
                    showPage(exc, 0, params.toArray());
                    return;
                } catch (Exception e) {
                    log.error("", e);
                    s.clear();
                    showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
                    return;
                }
                if (accountBlocker != null)
                    accountBlocker.unblock(s.getUserName());
                String target = URLParamUtil.getParams(uriFactory, exc).get("target");
                if (StringUtils.isEmpty(target))
                    target = "/";
                if (this.message != null)
                    exc.setResponse(Response.redirectWithout300(target, message).build());
                else
                    exc.setResponse(Response.redirectWithout300(target).build());
                s.authorize();
            } else {
                showPage(exc, 1);
            }
        }
    } else {
        wsi.handleRequest(exc);
    }
}
Also used : ResolverMap(com.predic8.membrane.core.resolver.ResolverMap) ParseException(com.floreysoft.jmte.message.ParseException) MalformedURLException(java.net.MalformedURLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 9 with Session

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

the class LoginInterceptor method handleRequest.

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    if (loginDialog.isLoginRequest(exc)) {
        loginDialog.handleLoginRequest(exc);
        return Outcome.RETURN;
    }
    Session s = sessionManager.getSession(exc);
    if (s != null && s.isPreAuthorized()) {
        if (tokenProvider == null) {
            s.authorize();
        }
    } else if (s == null || !s.isAuthorized()) {
        return loginDialog.redirectToLogin(exc);
    }
    applyBackendAuthorization(exc, s);
    return super.handleRequest(exc);
}
Also used : Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 10 with Session

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

the class AuthorizationCodeFlow method getValidIdTokenClaims.

private JwtGenerator.Claim[] getValidIdTokenClaims(SessionManager.Session session) {
    ClaimsParameter cp = new ClaimsParameter(authServer.getClaimList().getSupportedClaims(), session.getUserAttributes().get(ParamNames.CLAIMS));
    ArrayList<JwtGenerator.Claim> claims = new ArrayList<JwtGenerator.Claim>();
    if (cp.hasClaims()) {
        for (String claim : cp.getIdTokenClaims()) claims.add(new JwtGenerator.Claim(claim, session.getUserAttributes().get(ClaimRenamer.convert(claim))));
    }
    return claims.toArray(new JwtGenerator.Claim[0]);
}
Also used : JwtGenerator(com.predic8.membrane.core.interceptor.oauth2.tokengenerators.JwtGenerator) ArrayList(java.util.ArrayList) ClaimsParameter(com.predic8.membrane.core.interceptor.oauth2.parameter.ClaimsParameter)

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