Search in sources :

Example 6 with AuthChainType

use of com.tremolosecurity.config.xml.AuthChainType in project OpenUnison by TremoloSecurity.

the class SamlTransaction method doFederation.

private void doFederation(HttpServletRequest request, HttpServletResponse response, String issuer, String nameID, String authnCtx, String url, String relayState, Saml2Trust trust) throws Exception, ServletException, IOException {
    if (authnCtx == null) {
        authnCtx = trust.params.get("defaultAuthCtx").getValues().get(0);
    }
    if (nameID == null) {
        nameID = trust.params.get("defaultNameId").getValues().get(0);
    }
    String authChain = trust.authChainMap.get(authnCtx);
    if (authChain == null) {
        StringBuffer b = new StringBuffer();
        b.append("IdP does not have an authenticaiton chain configured with '").append(authnCtx).append("'");
        throw new Exception(b.toString());
    }
    String nameIDAttr = trust.nameIDMap.get(nameID);
    if (logger.isDebugEnabled()) {
        logger.debug("Auth Chain : '" + authChain + "'");
        logger.debug("NameID Attr : '" + nameIDAttr + "'");
    }
    HttpSession session = request.getSession();
    AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    AuthChainType act = holder.getConfig().getAuthChains().get(authChain);
    if (url == null) {
        url = trust.params.get("httpPostRespURL").getValues().get(0);
    }
    SamlTransaction transaction = new SamlTransaction();
    transaction.issuer = issuer;
    transaction.nameIDAttr = nameIDAttr;
    transaction.nameIDFormat = nameID;
    transaction.postToURL = url;
    transaction.authnCtxName = authnCtx;
    transaction.relayState = relayState;
    session.setAttribute(Saml2Idp.TRANSACTION_DATA, transaction);
    if (authData == null || !authData.isAuthComplete() && !(authData.getAuthLevel() < act.getLevel())) {
        nextAuth(request, response, session, false, act);
    } else {
        if (authData.getAuthLevel() < act.getLevel()) {
            // step up authentication, clear existing auth data
            /*AuthController controller = ((AuthController) session.getAttribute(AuthSys.AUTH_CTL));
				controller.setHolder(null);
				for (AuthStep as : controller.getAuthSteps()) {
					as.setExecuted(false);
					as.setSuccess(false);
				}*/
            session.removeAttribute(ProxyConstants.AUTH_CTL);
            holder.getConfig().createAnonUser(session);
            nextAuth(request, response, session, false, act);
        } else {
            // chain.doFilter(req, resp);
            // next.nextSys((HttpServletRequest) req, (HttpServletResponse) resp);
            StringBuffer b = genFinalURL(request);
            response.sendRedirect(b.toString());
        }
    }
}
Also used : UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) HttpSession(javax.servlet.http.HttpSession) AuthController(com.tremolosecurity.proxy.auth.AuthController) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) ServletException(javax.servlet.ServletException) SignatureException(java.security.SignatureException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAXException(org.xml.sax.SAXException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InitializationException(org.opensaml.core.config.InitializationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 7 with AuthChainType

use of com.tremolosecurity.config.xml.AuthChainType in project OpenUnison by TremoloSecurity.

the class UnisonConfigManagerImpl method loadAuthMechs.

/* (non-Javadoc)
	 * @see com.tremolosecurity.config.util.ConfigManager#loadAuthMechs()
	 */
/* (non-Javadoc)
	 * @see com.tremolosecurity.config.util.UnisonConfigManager#loadAuthMechs()
	 */
@Override
public void loadAuthMechs() throws ServletException {
    try {
        this.mechs = new HashMap<String, AuthMechanism>();
        // UnisonConfigManagerImpl tremoloCfg = (UnisonConfigManagerImpl) ctx.getAttribute(ConfigFilter.TREMOLO_CONFIG);
        if (getCfg().getAuthMechs() != null) {
            Iterator<MechanismType> mechs = getCfg().getAuthMechs().getMechanism().iterator();
            while (mechs.hasNext()) {
                MechanismType mt = mechs.next();
                initializeAuthenticationMechanism(mt);
            }
        }
    } catch (Exception e) {
        throw new ServletException("Could not initialize Auth Mechanism Filter", e);
    }
    for (String key : this.authChains.keySet()) {
        AuthChainType act = this.authChains.get(key);
        if (act.getLevel() == 0) {
            this.anonAct = act;
            String mechName = act.getAuthMech().get(0).getName();
            this.anonAuthMech = (AnonAuth) this.getAuthMech(this.authMechs.get(mechName).getUri());
        }
    }
    if (this.anonAuthMech == null) {
        this.anonAct = new AuthChainType();
        this.anonAct.setFinishOnRequiredSucess(true);
        this.anonAct.setLevel(0);
        this.anonAct.setName("anon");
        this.anonAuthMech = new AnonAuth();
    }
    if (this.alwaysFailAuth == null) {
        this.alwaysFailAuth = new AlwaysFail();
        String failAuthUri = this.ctxPath + "/fail";
        this.mechs.put(failAuthUri, alwaysFailAuth);
        MechanismType fmt = new MechanismType();
        fmt.setClassName("com.tremolosecurity.proxy.auth.AlwaysFail");
        fmt.setInit(new ConfigType());
        fmt.setParams(new ParamListType());
        fmt.setName("fail");
        fmt.setUri(failAuthUri);
        if (this.cfg.getAuthMechs() == null) {
            this.cfg.setAuthMechs(new AuthMechTypes());
        }
        this.cfg.getAuthMechs().getMechanism().add(fmt);
        this.alwaysFailAuthMech = fmt;
    }
    for (String key : this.authChains.keySet()) {
        AuthChainType act = this.authChains.get(key);
        for (AuthMechType amt : act.getAuthMech()) {
            if (amt.getName().equals(this.alwaysFailAuthMech.getName())) {
                this.authFailChain = act;
                break;
            }
        }
    }
    if (this.authFailChain == null) {
        this.authFailChain = new AuthChainType();
        this.authFailChain.setLevel(0);
        this.authFailChain.setName("alwaysfail");
        AuthMechType amt = new AuthMechType();
        amt.setName(this.alwaysFailAuthMech.getName());
        amt.setRequired("required");
        amt.setParams(new AuthMechParamType());
        this.authFailChain.getAuthMech().add(amt);
    }
    try {
        if (this.getCfg().getAuthMechs() != null && this.getCfg().getAuthMechs().getDynamicAuthMechs() != null && this.getCfg().getAuthMechs().getDynamicAuthMechs().isEnabled()) {
            DynamicPortalUrlsType dynamicAuthMechs = this.getCfg().getAuthMechs().getDynamicAuthMechs();
            String className = dynamicAuthMechs.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicAuthMechs.getParams()) {
                Attribute attr = cfgAttrs.get(pt.getName());
                if (attr == null) {
                    attr = new Attribute(pt.getName());
                    cfgAttrs.put(pt.getName(), attr);
                }
                attr.getValues().add(pt.getValue());
            }
            DynamicAuthMechs dynCustomAuMechs = (DynamicAuthMechs) Class.forName(className).newInstance();
            dynCustomAuMechs.loadDynamicAuthMechs(this, this.getProvisioningEngine(), cfgAttrs);
        }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ProvisioningException e) {
        throw new ServletException("Could not initialize authentication mechanisms", e);
    }
}
Also used : AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) AnonAuth(com.tremolosecurity.proxy.auth.AnonAuth) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ServletException(javax.servlet.ServletException) DynamicAuthMechs(com.tremolosecurity.proxy.dynamicloaders.DynamicAuthMechs) AuthMechanism(com.tremolosecurity.proxy.auth.AuthMechanism) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) MechanismType(com.tremolosecurity.config.xml.MechanismType) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) ConfigType(com.tremolosecurity.config.xml.ConfigType) ParamListType(com.tremolosecurity.config.xml.ParamListType) AuthMechTypes(com.tremolosecurity.config.xml.AuthMechTypes) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) KeyStoreException(java.security.KeyStoreException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LDAPException(com.novell.ldap.LDAPException) AzException(com.tremolosecurity.proxy.az.AzException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) ParamType(com.tremolosecurity.config.xml.ParamType) AlwaysFail(com.tremolosecurity.proxy.auth.AlwaysFail) DynamicPortalUrlsType(com.tremolosecurity.config.xml.DynamicPortalUrlsType)

Example 8 with AuthChainType

use of com.tremolosecurity.config.xml.AuthChainType in project OpenUnison by TremoloSecurity.

the class JITAuthMech method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp, AuthStep as) throws ServletException, IOException {
    // HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    // SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) req).getSession();
    UrlHolder holder = (UrlHolder) req.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String nameAttr = null;
    if (authParams.get("nameAttr") == null) {
        throw new ServletException("No name attribute");
    }
    nameAttr = authParams.get("nameAttr").getValues().get(0);
    String workflowName;
    if (authParams.get("workflowName") == null) {
        throw new ServletException("No workflow specified");
    }
    workflowName = authParams.get("workflowName").getValues().get(0);
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    AuthInfo authInfo = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    try {
        holder.getConfig().getProvisioningEngine().getWorkFlow(workflowName).executeWorkflow(authInfo, nameAttr);
        as.setSuccess(true);
    } catch (ProvisioningException e) {
        StringBuffer b = new StringBuffer();
        b.append("Could not execute workflow '").append(workflowName).append("' on '").append(authInfo.getUserDN()).append("'");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter err = new PrintWriter(new OutputStreamWriter(baos));
        e.printStackTrace(err);
        Throwable t = e.getCause();
        while (t != null) {
            t.printStackTrace(err);
            t = t.getCause();
        }
        logger.error(b.toString() + new String(baos.toByteArray()));
        as.setSuccess(false);
        logger.warn("Could not execute workflow " + workflowName + " for " + authInfo.getUserDN(), e);
    }
    holder.getConfig().getAuthManager().nextAuth(req, resp, session, false);
}
Also used : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) LDAPAttribute(com.novell.ldap.LDAPAttribute) HashMap(java.util.HashMap) TremoloHttpSession(com.tremolosecurity.proxy.TremoloHttpSession) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) AuthController(com.tremolosecurity.proxy.auth.AuthController) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) OutputStreamWriter(java.io.OutputStreamWriter) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) PrintWriter(java.io.PrintWriter)

Example 9 with AuthChainType

use of com.tremolosecurity.config.xml.AuthChainType in project OpenUnison by TremoloSecurity.

the class SMSAuth method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    String from = authParams.get("fromNumber").getValues().get(0);
    String toAttrName = authParams.get("toAttrName").getValues().get(0);
    String redirectForm = authParams.get("redirectForm").getValues().get(0);
    String message = authParams.get("message").getValues().get(0);
    // Key Options
    if (authParams.get("keyLength") == null) {
        throw new ServletException("Key Length not set");
    }
    int keyLen = Integer.parseInt(authParams.get("keyLength").getValues().get(0));
    boolean useLowerCase = authParams.get("useLowerCase") != null && authParams.get("useLowerCase").getValues().get(0).equalsIgnoreCase("true");
    boolean useUpperCase = authParams.get("useUpperCase") != null && authParams.get("useUpperCase").getValues().get(0).equalsIgnoreCase("true");
    boolean useNumbers = authParams.get("useNumbers") != null && authParams.get("useNumbers").getValues().get(0).equalsIgnoreCase("true");
    // authParams.get("useSpecial") != null && authParams.get("useSpecial").getValues().get(0).equalsIgnoreCase("true");
    boolean useSpecial = false;
    if (!(useLowerCase || useUpperCase || useNumbers || useSpecial)) {
        throw new ServletException("At least one character type must be chosen");
    }
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    if (session.getAttribute("TREMOLO_SMS_KEY") == null) {
        GenPasswd gp = new GenPasswd(keyLen, useUpperCase, useLowerCase, useNumbers, useSpecial);
        AuthInfo user = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
        String to = user.getAttribs().get(toAttrName).getValues().get(0);
        String key = gp.getPassword();
        message = message.replaceAll("[$][{]key[}]", key);
        session.setAttribute("TREMOLO_SMS_KEY", key);
        sendSMS(authParams, from, message, to);
    }
    response.sendRedirect(redirectForm);
}
Also used : GenPasswd(com.tremolosecurity.provisioning.util.GenPasswd) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) UrlHolder(com.tremolosecurity.config.util.UrlHolder) AuthChainType(com.tremolosecurity.config.xml.AuthChainType)

Example 10 with AuthChainType

use of com.tremolosecurity.config.xml.AuthChainType in project OpenUnison by TremoloSecurity.

the class GithubAuthMech method doGet.

public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session.getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    MyVDConnection myvd = cfg.getMyVD();
    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String clientid = authParams.get("clientid").getValues().get(0);
    String secret = authParams.get("secretid").getValues().get(0);
    String idpURL = authParams.get("idpURL") != null ? authParams.get("idpURL").getValues().get(0) : "https://github.com/login/oauth/authorize";
    String scope = authParams.get("scope").getValues().get(0);
    boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
    String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
    String uidAttr = authParams.get("uidAttr").getValues().get(0);
    String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);
    // authParams.get("forceAuthentication") != null ? authParams.get("forceAuthentication").getValues().get(0).equalsIgnoreCase("true") : false;
    boolean forceAuth = true;
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
    StringBuffer b = new StringBuffer();
    URL reqURL = new URL(request.getRequestURL().toString());
    b.append(reqURL.getProtocol()).append("://").append(reqURL.getHost());
    if (reqURL.getPort() != -1) {
        b.append(":").append(reqURL.getPort());
    }
    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());
    AuthMechType amt = act.getAuthMech().get(as.getId());
    String authMechName = amt.getName();
    b.append(holder.getConfig().getContextPath()).append(cfg.getAuthMechs().get(authMechName).getUri());
    String loadTokenURL = authParams.get("loadTokenURL") != null ? authParams.get("loadTokenURL").getValues().get(0) : "https://github.com/login/oauth/access_token";
    if (request.getParameter("state") == null) {
        // initialize openidconnect
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        request.getSession().setAttribute("UNISON_OPENIDCONNECT_STATE", state);
        StringBuffer redirToSend = new StringBuffer();
        redirToSend.append(idpURL).append("?client_id=").append(URLEncoder.encode(clientid, "UTF-8")).append("&scope=").append(URLEncoder.encode(scope, "UTF-8")).append("&state=").append(URLEncoder.encode("security_token=", "UTF-8")).append(URLEncoder.encode(state, "UTF-8"));
        response.sendRedirect(redirToSend.toString());
    } else {
        String stateFromURL = request.getParameter("state");
        stateFromURL = URLDecoder.decode(stateFromURL, "UTF-8");
        stateFromURL = stateFromURL.substring(stateFromURL.indexOf('=') + 1);
        String stateFromSession = (String) request.getSession().getAttribute("UNISON_OPENIDCONNECT_STATE");
        if (!stateFromSession.equalsIgnoreCase(stateFromURL)) {
            throw new ServletException("Invalid State");
        }
        HttpUriRequest post = null;
        try {
            post = RequestBuilder.post().setUri(new java.net.URI(loadTokenURL)).addParameter("code", request.getParameter("code")).addParameter("client_id", clientid).addParameter("client_secret", secret).build();
        } catch (URISyntaxException e) {
            throw new ServletException("Could not create post request");
        }
        BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();
        try {
            CloseableHttpResponse httpResp = http.execute(post);
            BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            StringBuffer token = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                token.append(line);
            }
            List<NameValuePair> params = URLEncodedUtils.parse(token.toString(), Charset.defaultCharset());
            String accessToken = null;
            for (NameValuePair nvp : params) {
                if (nvp.getName().equals("access_token")) {
                    accessToken = nvp.getValue();
                }
            }
            if (accessToken == null) {
                throw new ServletException("Could not get authorization toekn : " + token);
            }
            httpResp.close();
            Gson gson = new Gson();
            HttpGet get = new HttpGet("https://api.github.com/user");
            get.addHeader("Authorization", new StringBuilder().append("Bearer ").append(accessToken).toString());
            // Store the bearer token for use by Unison
            request.getSession().setAttribute(bearerTokenName, accessToken);
            httpResp = http.execute(get);
            in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            token.setLength(0);
            line = null;
            while ((line = in.readLine()) != null) {
                token.append(line);
            }
            httpResp.close();
            Map jwtNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());
            ;
            if (jwtNVP == null) {
                as.setSuccess(false);
            } else {
                get = new HttpGet("https://api.github.com/user/emails");
                get.addHeader("Authorization", new StringBuilder().append("Bearer ").append(accessToken).toString());
                httpResp = http.execute(get);
                in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
                token.setLength(0);
                line = null;
                while ((line = in.readLine()) != null) {
                    token.append(line);
                }
                httpResp.close();
                JSONParser parser = new JSONParser();
                org.json.simple.JSONArray emails = (org.json.simple.JSONArray) parser.parse(token.toString());
                for (Object o : emails) {
                    org.json.simple.JSONObject emailObj = (org.json.simple.JSONObject) o;
                    boolean isPrimary = (Boolean) emailObj.get("primary");
                    if (isPrimary) {
                        jwtNVP.put("mail", emailObj.get("email"));
                    }
                }
                if (!linkToDirectory) {
                    loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);
                    as.setSuccess(true);
                } else {
                    lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, jwtNVP, defaultObjectClass);
                }
                get = new HttpGet("https://api.github.com/user/orgs");
                get.addHeader("Authorization", new StringBuilder().append("Bearer ").append(accessToken).toString());
                httpResp = http.execute(get);
                in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
                token.setLength(0);
                line = null;
                while ((line = in.readLine()) != null) {
                    token.append(line);
                }
                httpResp.close();
                parser = new JSONParser();
                org.json.simple.JSONArray orgs = (org.json.simple.JSONArray) parser.parse(token.toString());
                Attribute userOrgs = new Attribute("githubOrgs");
                Attribute userTeams = new Attribute("githubTeams");
                for (Object o : orgs) {
                    org.json.simple.JSONObject org = (org.json.simple.JSONObject) o;
                    String orgName = (String) org.get("login");
                    userOrgs.getValues().add(orgName);
                    HttpUriRequest graphql = RequestBuilder.post().addHeader(new BasicHeader("Authorization", "Bearer " + accessToken)).setUri("https://api.github.com/graphql").setEntity(new StringEntity("{\"query\":\"{organization(login: \\\"" + orgName + "\\\") { teams(first: 100, userLogins: [\\\"" + jwtNVP.get("login") + "\\\"]) { totalCount edges {node {name description}}}}}\"}")).build();
                    httpResp = http.execute(graphql);
                    in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
                    token.setLength(0);
                    line = null;
                    while ((line = in.readLine()) != null) {
                        token.append(line);
                    }
                    httpResp.close();
                    org.json.simple.JSONObject root = (org.json.simple.JSONObject) parser.parse(token.toString());
                    org.json.simple.JSONObject data = (org.json.simple.JSONObject) root.get("data");
                    org.json.simple.JSONObject organization = (org.json.simple.JSONObject) data.get("organization");
                    org.json.simple.JSONObject teams = (org.json.simple.JSONObject) organization.get("teams");
                    org.json.simple.JSONArray edges = (org.json.simple.JSONArray) teams.get("edges");
                    for (Object oi : edges) {
                        org.json.simple.JSONObject edge = (org.json.simple.JSONObject) oi;
                        org.json.simple.JSONObject node = (org.json.simple.JSONObject) edge.get("node");
                        userTeams.getValues().add(orgName + "/" + node.get("name"));
                    }
                }
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo().getAttribs().put("githubOrgs", userOrgs);
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo().getAttribs().put("githubTeams", userTeams);
                String redirectToURL = request.getParameter("target");
                if (redirectToURL != null && !redirectToURL.isEmpty()) {
                    reqHolder.setURL(redirectToURL);
                }
            }
            holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        } catch (ParseException e) {
            throw new ServletException("Could not parse orgs", e);
        } finally {
            if (bhcm != null) {
                bhcm.close();
            }
            if (http != null) {
                http.close();
            }
        }
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) LDAPAttribute(com.novell.ldap.LDAPAttribute) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) Gson(com.google.gson.Gson) URISyntaxException(java.net.URISyntaxException) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) URL(java.net.URL) HttpServletRequest(javax.servlet.http.HttpServletRequest) UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) MyVDConnection(com.tremolosecurity.proxy.myvd.MyVDConnection) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) HttpSession(javax.servlet.http.HttpSession) JSONArray(org.jose4j.json.internal.json_simple.JSONArray) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) SecureRandom(java.security.SecureRandom) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) BufferedReader(java.io.BufferedReader) BigInteger(java.math.BigInteger) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) HashMap(java.util.HashMap) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

AuthChainType (com.tremolosecurity.config.xml.AuthChainType)52 UrlHolder (com.tremolosecurity.config.util.UrlHolder)34 AuthMechType (com.tremolosecurity.config.xml.AuthMechType)34 HttpSession (javax.servlet.http.HttpSession)33 HashMap (java.util.HashMap)32 ServletException (javax.servlet.ServletException)32 Attribute (com.tremolosecurity.saml.Attribute)28 HttpServletRequest (javax.servlet.http.HttpServletRequest)28 IOException (java.io.IOException)21 AuthController (com.tremolosecurity.proxy.auth.AuthController)19 LDAPException (com.novell.ldap.LDAPException)18 LDAPAttribute (com.novell.ldap.LDAPAttribute)17 AuthInfo (com.tremolosecurity.proxy.auth.AuthInfo)14 RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)13 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)12 MalformedURLException (java.net.MalformedURLException)10 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)9 ArrayList (java.util.ArrayList)9 LDAPEntry (com.novell.ldap.LDAPEntry)8