Search in sources :

Example 1 with URIFactory

use of com.predic8.membrane.core.util.URIFactory in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method init.

@Override
public void init(Router router) throws Exception {
    name = "OAuth 2 Client";
    setFlow(Flow.Set.REQUEST_RESPONSE);
    super.init(router);
    auth.init(router);
    statistics = new OAuth2Statistics();
    uriFactory = router.getUriFactory();
    if (sessionManager == null)
        sessionManager = new SessionManager();
    // TODO maybe do this differently as now the attribute in the bean is overwritten ( when set from external proxies.xml )
    sessionManager.setCookieName("SESSION_ID_CLIENT");
    sessionManager.init(router);
    if (loginLocation != null) {
        wsi = new WebServerInterceptor();
        wsi.setDocBase(loginLocation);
        router.getResolverMap().resolve(ResolverMap.combine(router.getBaseLocation(), wsi.getDocBase(), "./index.html")).close();
        wsi.init(router);
    }
    if (publicURL == null)
        initPublicURLOnFirstExchange = true;
    else
        normalizePublicURL();
    firstInitWhenDynamicAuthorizationService = getAuthService().supportsDynamicRegistration();
    if (!getAuthService().supportsDynamicRegistration())
        firstInitWhenDynamicAuthorizationService = false;
    new CleanupThread(sessionManager).start();
}
Also used : CleanupThread(com.predic8.membrane.core.interceptor.authentication.session.CleanupThread) SessionManager(com.predic8.membrane.core.interceptor.authentication.session.SessionManager) WebServerInterceptor(com.predic8.membrane.core.interceptor.server.WebServerInterceptor)

Example 2 with URIFactory

use of com.predic8.membrane.core.util.URIFactory in project service-proxy by membrane.

the class LoadBalancingInterceptorTest method doTestGetDestinationURL.

private void doTestGetDestinationURL(String requestUri, String expectedUri) throws URISyntaxException {
    Exchange exc = new Exchange(null);
    exc.setRequest(new Request());
    exc.getRequest().setUri(URLUtil.getPathQuery(new URIFactory(), requestUri));
    exc.setOriginalRequestUri(requestUri);
    assertEquals(expectedUri, new Node("thomas-bayer.com", 80).getDestinationURL(exc));
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Node(com.predic8.membrane.core.interceptor.balancer.Node) Request(com.predic8.membrane.core.http.Request) URIFactory(com.predic8.membrane.core.util.URIFactory)

Example 3 with URIFactory

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

use of com.predic8.membrane.core.util.URIFactory in project service-proxy by membrane.

the class HTTPSchemaResolver method resolve.

public InputStream resolve(String url) throws ResourceRetrievalException {
    try {
        Exchange exc = new Request.Builder().method(Request.METHOD_GET).url(uriFactory, url).header(Header.USER_AGENT, Constants.PRODUCT_NAME + " " + Constants.VERSION).buildExchange();
        Response response = getHttpClient().call(exc).getResponse();
        response.readBody();
        if (response.getStatusCode() != 200) {
            ResourceRetrievalException rde = new ResourceRetrievalException(url, response.getStatusCode());
            throw rde;
        }
        return new ByteArrayInputStream(ByteUtil.getByteArrayData(response.getBodyAsStreamDecoded()));
    } catch (ResourceRetrievalException e) {
        throw e;
    } catch (Exception e) {
        ResourceRetrievalException rre = new ResourceRetrievalException(url, e);
        throw rre;
    }
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with URIFactory

use of com.predic8.membrane.core.util.URIFactory in project service-proxy by membrane.

the class OAuth2ResourceTest method getMockAuthServiceProxy.

private ServiceProxy getMockAuthServiceProxy() throws IOException {
    ServiceProxy sp = new ServiceProxy(new ServiceProxyKey(serverPort), null, 99999);
    WellknownFile wkf = new WellknownFile();
    wkf.setIssuer(getServerAddress());
    wkf.setAuthorizationEndpoint(getServerAddress() + "/auth");
    wkf.setTokenEndpoint(getServerAddress() + "/token");
    wkf.setUserinfoEndpoint(getServerAddress() + "/userinfo");
    wkf.setRevocationEndpoint(getServerAddress() + "/revoke");
    wkf.setJwksUri(getServerAddress() + "/certs");
    wkf.setSupportedResponseTypes("code token");
    wkf.setSupportedSubjectType("public");
    wkf.setSupportedIdTokenSigningAlgValues("RS256");
    wkf.setSupportedScopes("openid email profile");
    wkf.setSupportedTokenEndpointAuthMethods("client_secret_post");
    wkf.setSupportedClaims("sub email username");
    wkf.init(new HttpRouter());
    sp.getInterceptors().add(new AbstractInterceptor() {

        SecureRandom rand = new SecureRandom();

        @Override
        public synchronized Outcome handleRequest(Exchange exc) throws Exception {
            if (exc.getRequestURI().endsWith("/.well-known/openid-configuration")) {
                exc.setResponse(Response.ok(wkf.getWellknown()).build());
            } else if (exc.getRequestURI().startsWith("/auth?")) {
                Map<String, String> params = URLParamUtil.getParams(new URIFactory(), exc);
                exc.setResponse(Response.redirect(getClientAddress() + "/oauth2callback?code=1234&state=" + params.get("state"), false).build());
            } else if (exc.getRequestURI().startsWith("/token")) {
                ObjectMapper om = new ObjectMapper();
                Map<String, String> res = new HashMap<>();
                res.put("access_token", new BigInteger(130, rand).toString(32));
                res.put("token_type", "bearer");
                res.put("expires_in", "1");
                res.put("refresh_token", new BigInteger(130, rand).toString(32));
                exc.setResponse(Response.ok(om.writeValueAsString(res)).contentType("application/json").build());
            } else if (exc.getRequestURI().startsWith("/userinfo")) {
                ObjectMapper om = new ObjectMapper();
                Map<String, String> res = new HashMap<>();
                res.put("username", "dummy");
                exc.setResponse(Response.ok(om.writeValueAsString(res)).contentType("application/json").build());
            }
            if (exc.getResponse() == null)
                exc.setResponse(Response.notFound().build());
            return Outcome.RETURN;
        }
    });
    return sp;
}
Also used : AbstractInterceptor(com.predic8.membrane.core.interceptor.AbstractInterceptor) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) ServiceProxyKey(com.predic8.membrane.core.rules.ServiceProxyKey) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) Outcome(com.predic8.membrane.core.interceptor.Outcome) URIFactory(com.predic8.membrane.core.util.URIFactory) BigInteger(java.math.BigInteger) HttpRouter(com.predic8.membrane.core.HttpRouter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

Exchange (com.predic8.membrane.core.exchange.Exchange)4 Response (com.predic8.membrane.core.http.Response)4 URIFactory (com.predic8.membrane.core.util.URIFactory)4 ParseException (com.floreysoft.jmte.message.ParseException)2 Request (com.predic8.membrane.core.http.Request)2 SessionManager (com.predic8.membrane.core.interceptor.authentication.session.SessionManager)2 IOException (java.io.IOException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 HttpRouter (com.predic8.membrane.core.HttpRouter)1 AbstractInterceptor (com.predic8.membrane.core.interceptor.AbstractInterceptor)1 LogInterceptor (com.predic8.membrane.core.interceptor.LogInterceptor)1 Outcome (com.predic8.membrane.core.interceptor.Outcome)1 CleanupThread (com.predic8.membrane.core.interceptor.authentication.session.CleanupThread)1 Session (com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)1 Node (com.predic8.membrane.core.interceptor.balancer.Node)1 Client (com.predic8.membrane.core.interceptor.oauth2.Client)1 WebServerInterceptor (com.predic8.membrane.core.interceptor.server.WebServerInterceptor)1 ResolverMap (com.predic8.membrane.core.resolver.ResolverMap)1 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)1