Search in sources :

Example 1 with LoadUserData

use of com.tremolosecurity.unison.proxy.auth.openidconnect.sdk.LoadUserData in project OpenUnison by TremoloSecurity.

the class OpenIDConnectAuthMech 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 idpURL;
    String loadTokenURL;
    if (authParams.get("issuer") != null) {
        StringBuffer b = new StringBuffer();
        String issuer = authParams.get("issuer").getValues().get(0);
        b.append(issuer);
        if (issuer.charAt(issuer.length() - 1) != '/') {
            b.append('/');
        }
        b.append(".well-known/openid-configuration");
        String discoveryUrl = b.toString();
        OidcIdpUrls idp = this.idpUrls.get(discoveryUrl);
        if (idp == null) {
            idp = new OidcIdpUrls();
            this.idpUrls.put(discoveryUrl, idp);
            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 {
                HttpGet get = new HttpGet(b.toString());
                CloseableHttpResponse resp = http.execute(get);
                if (resp.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(resp.getEntity());
                    resp.close();
                    JSONParser parser = new JSONParser();
                    org.json.simple.JSONObject root = (org.json.simple.JSONObject) parser.parse(json);
                    idp.setIdpUrl((String) root.get("authorization_endpoint"));
                    idp.setTokenUrl((String) root.get("token_endpoint"));
                    idp.setUserInfoUrl((String) root.get("userinfo_endpoint"));
                } else {
                    idp.setIdpUrl(authParams.get("idpURL").getValues().get(0));
                    idp.setTokenUrl(loadTokenURL = authParams.get("loadTokenURL").getValues().get(0));
                }
            } catch (ParseException e) {
                throw new ServletException("Could not parse discovery document", e);
            } finally {
                try {
                    http.close();
                } catch (Throwable e) {
                }
                bhcm.close();
            }
        }
        request.setAttribute(OIDC_IDP, idp);
        idpURL = idp.getIdpUrl();
        loadTokenURL = idp.getTokenUrl();
    } else {
        idpURL = authParams.get("idpURL").getValues().get(0);
        loadTokenURL = authParams.get("loadTokenURL").getValues().get(0);
    }
    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 responseType = authParams.get("responseType").getValues().get(0);
    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 userLookupClassName = authParams.get("userLookupClassName").getValues().get(0);
    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);
    boolean forceAuth = authParams.get("forceAuthentication") != null ? authParams.get("forceAuthentication").getValues().get(0).equalsIgnoreCase("true") : 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(ProxyTools.getInstance().getHttpsUrl(request.getRequestURL().toString(), request));
    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 hd = authParams.get("hd").getValues().get(0);
    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("&response_type=").append(URLEncoder.encode(responseType, "UTF-8")).append("&scope=").append(URLEncoder.encode(scope, "UTF-8")).append("&redirect_uri=").append(URLEncoder.encode(b.toString(), "UTF-8")).append("&state=").append(URLEncoder.encode("security_token=", "UTF-8")).append(URLEncoder.encode(state, "UTF-8"));
        if (forceAuth) {
            redirToSend.append("&max_age=0");
        }
        if (hd != null && !hd.isEmpty()) {
            redirToSend.append("&hd=").append(hd);
        }
        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).addParameter("redirect_uri", b.toString()).addParameter("grant_type", "authorization_code").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();
        CloseableHttpResponse httpResp = http.execute(post);
        if (httpResp.getStatusLine().getStatusCode() != 200) {
            logger.error("Could not retrieve token : " + httpResp.getStatusLine().getStatusCode() + " / " + httpResp.getStatusLine().getReasonPhrase());
            as.setSuccess(false);
            holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
        StringBuffer token = new StringBuffer();
        String line = null;
        while ((line = in.readLine()) != null) {
            token.append(line);
        }
        httpResp.close();
        bhcm.close();
        Gson gson = new Gson();
        Map tokenNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());
        String accessToken;
        // Store the bearer token for use by Unison
        request.getSession().setAttribute(bearerTokenName, tokenNVP.get("access_token"));
        Map jwtNVP = null;
        LoadUserData loadUser = null;
        try {
            loadUser = (LoadUserData) Class.forName(userLookupClassName).newInstance();
            jwtNVP = loadUser.loadUserAttributesFromIdP(request, response, cfg, authParams, tokenNVP);
        } catch (Exception e) {
            throw new ServletException("Could not load user data", e);
        }
        if (hd != null && !hd.isEmpty()) {
            String hdFromIdToken = (String) jwtNVP.get("hd");
            if (hdFromIdToken != null && !hdFromIdToken.isEmpty()) {
                if (!hdFromIdToken.equalsIgnoreCase(hd)) {
                    as.setSuccess(false);
                    String redirectToURL = request.getParameter("target");
                    if (redirectToURL != null && !redirectToURL.isEmpty()) {
                        reqHolder.setURL(redirectToURL);
                    }
                }
            } else {
                as.setSuccess(false);
                String redirectToURL = request.getParameter("target");
                if (redirectToURL != null && !redirectToURL.isEmpty()) {
                    reqHolder.setURL(redirectToURL);
                }
            }
        }
        if (jwtNVP == null) {
            as.setSuccess(false);
        } else {
            if (!linkToDirectory) {
                loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);
                as.setSuccess(true);
            } else {
                lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, jwtNVP, defaultObjectClass);
            }
            String redirectToURL = request.getParameter("target");
            if (redirectToURL != null && !redirectToURL.isEmpty()) {
                reqHolder.setURL(redirectToURL);
            }
        }
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
    }
}
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) ServletException(javax.servlet.ServletException) UrlHolder(com.tremolosecurity.config.util.UrlHolder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) LoadUserData(com.tremolosecurity.unison.proxy.auth.openidconnect.sdk.LoadUserData) 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) InputStreamReader(java.io.InputStreamReader) HttpSession(javax.servlet.http.HttpSession) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) SecureRandom(java.security.SecureRandom) AuthController(com.tremolosecurity.proxy.auth.AuthController) ConfigManager(com.tremolosecurity.config.util.ConfigManager) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) LDAPException(com.novell.ldap.LDAPException) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) BufferedReader(java.io.BufferedReader) BigInteger(java.math.BigInteger) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Gson (com.google.gson.Gson)1 LDAPAttribute (com.novell.ldap.LDAPAttribute)1 LDAPException (com.novell.ldap.LDAPException)1 ConfigManager (com.tremolosecurity.config.util.ConfigManager)1 UrlHolder (com.tremolosecurity.config.util.UrlHolder)1 AuthChainType (com.tremolosecurity.config.xml.AuthChainType)1 AuthMechType (com.tremolosecurity.config.xml.AuthMechType)1 AuthController (com.tremolosecurity.proxy.auth.AuthController)1 RequestHolder (com.tremolosecurity.proxy.auth.RequestHolder)1 MyVDConnection (com.tremolosecurity.proxy.myvd.MyVDConnection)1 Attribute (com.tremolosecurity.saml.Attribute)1 LoadUserData (com.tremolosecurity.unison.proxy.auth.openidconnect.sdk.LoadUserData)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 BigInteger (java.math.BigInteger)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 SecureRandom (java.security.SecureRandom)1 HashMap (java.util.HashMap)1