Search in sources :

Example 1 with JSONParser

use of org.jose4j.json.internal.json_simple.parser.JSONParser in project java by kubernetes-client.

the class OpenIDConnectAuthenticator method refreshOidcToken.

/**
 * Refreshes the OpenID Connect id_token
 *
 * @param clientId from client-id
 * @param refreshToken from refresh-token
 * @param clientSecret from client-secret
 * @param sslContext to support TLS with a self signed certificate in
 *     idp-certificate-authority-data
 * @param tokenURL the url for refreshing the token
 * @return
 */
private JSONObject refreshOidcToken(String clientId, String refreshToken, String clientSecret, SSLContext sslContext, String tokenURL) {
    try {
        URL tokenEndpoint = new URL(tokenURL);
        HttpsURLConnection https = (HttpsURLConnection) tokenEndpoint.openConnection();
        https.setRequestMethod("POST");
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
        // per https://tools.ietf.org/html/rfc6749#section-2.3 the secret should be a header,
        // not in
        // the body
        String credentials = Base64.getEncoder().encodeToString(new StringBuilder().append(clientId).append(':').append(clientSecret).toString().getBytes(StandardCharsets.UTF_8));
        https.setRequestProperty("Authorization", new StringBuilder().append("Basic ").append(credentials).toString());
        https.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        https.setDoOutput(true);
        String urlData = new StringBuilder().append("refresh_token=").append(URLEncoder.encode(refreshToken, "UTF-8")).append("&grant_type=refresh_token").toString();
        OutputStream ou = https.getOutputStream();
        ou.write(urlData.getBytes(StandardCharsets.UTF_8));
        ou.flush();
        ou.close();
        int code = https.getResponseCode();
        if (code != HttpsURLConnection.HTTP_OK) {
            throw new RuntimeException(new StringBuilder().append("Invalid response code for token retrieval - ").append(code).toString());
        }
        Scanner scanner = new Scanner(https.getInputStream(), StandardCharsets.UTF_8.name());
        String json = scanner.useDelimiter("\\A").next();
        return (JSONObject) new JSONParser().parse(json);
    } catch (Throwable t) {
        throw new RuntimeException("Could not refresh token", t);
    }
}
Also used : Scanner(java.util.Scanner) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) OutputStream(java.io.OutputStream) JSONParser(org.jose4j.json.internal.json_simple.parser.JSONParser) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 2 with JSONParser

use of org.jose4j.json.internal.json_simple.parser.JSONParser in project java by kubernetes-client.

the class OpenIDConnectAuthenticator method loadTokenURL.

/**
 * Determines the token url
 *
 * @param issuer from the idp-issuer-url
 * @param sslContext to support TLS with a self signed certificate in
 *     idp-certificate-authority-data
 * @return
 */
private String loadTokenURL(String issuer, SSLContext sslContext) {
    StringBuilder wellKnownUrl = new StringBuilder();
    wellKnownUrl.append(issuer);
    if (!issuer.endsWith("/")) {
        wellKnownUrl.append("/");
    }
    wellKnownUrl.append(".well-known/openid-configuration");
    try {
        URL wellKnown = new URL(wellKnownUrl.toString());
        HttpsURLConnection https = (HttpsURLConnection) wellKnown.openConnection();
        https.setRequestMethod("GET");
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
        https.setUseCaches(false);
        int code = https.getResponseCode();
        if (code != HttpsURLConnection.HTTP_OK) {
            throw new RuntimeException(new StringBuilder().append("Invalid response code for issuer - ").append(code).toString());
        }
        Scanner scanner = new Scanner(https.getInputStream(), StandardCharsets.UTF_8.name());
        String json = scanner.useDelimiter("\\A").next();
        JSONObject wellKnownJson = (JSONObject) new JSONParser().parse(json);
        return (String) wellKnownJson.get("token_endpoint");
    } catch (IOException | ParseException e) {
        throw new RuntimeException("Could not refresh", e);
    }
}
Also used : Scanner(java.util.Scanner) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) JSONParser(org.jose4j.json.internal.json_simple.parser.JSONParser) IOException(java.io.IOException) ParseException(org.jose4j.json.internal.json_simple.parser.ParseException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 3 with JSONParser

use of org.jose4j.json.internal.json_simple.parser.JSONParser in project open-ecard by ecsec.

the class VersionUpdateLoader method loadVersionUpdateList.

public VersionUpdateList loadVersionUpdateList() throws IllegalArgumentException {
    try {
        // load proxy if one is available
        // make sure it is initialized
        ProxySettings.getDefault();
        List<Proxy> proxies = ProxySelector.getDefault().select(updateUrl.toURI());
        Proxy p = Proxy.NO_PROXY;
        for (Proxy next : proxies) {
            if (next.type() != Proxy.Type.DIRECT) {
                LOG.debug("Found a proxy for the update connection.");
                p = next;
                break;
            }
        }
        LOG.info("Trying to load version list.");
        URLConnection con = updateUrl.openConnection(p);
        con.connect();
        InputStream in = con.getInputStream();
        Reader r = new InputStreamReader(in, StandardCharsets.UTF_8);
        JSONObject rootObj = (JSONObject) new JSONParser().parse(r);
        // get package specific download page
        String downloadPageString = (String) rootObj.get(pkgType + "_download_page");
        // access package specific list
        JSONArray updatesRaw = (JSONArray) rootObj.get(pkgType);
        ArrayList<VersionUpdate> updates = new ArrayList<>();
        for (Object ur : updatesRaw) {
            try {
                VersionUpdate next = VersionUpdate.fromJson((JSONObject) ur);
                updates.add(next);
            } catch (InvalidUpdateDefinition ex) {
                LOG.warn("Invalid version info contained in update list.", ex);
                throw new IllegalArgumentException("Invalid version info contained in update list.", ex);
            }
        }
        // make sure the versions are in the correct order
        Collections.sort(updates);
        VersionUpdateList list = new VersionUpdateList(updates, new URL(downloadPageString));
        LOG.info("Successfully retrieved version update list.");
        return list;
    } catch (IOException ex) {
        LOG.error("Failed to retrieve update list from server.", ex);
        throw new IllegalArgumentException("Failed to retrieve update list from server.", ex);
    } catch (NullPointerException ex) {
        LOG.warn("Package type {} not supported in update list.", pkgType);
        throw new IllegalArgumentException("Package type " + pkgType + " not supported in update list.", ex);
    } catch (URISyntaxException ex) {
        String msg = "Failed to convert Update URL to a URI.";
        LOG.error(msg, ex);
        throw new IllegalArgumentException(msg, ex);
    } catch (ParseException ex) {
        String msg = "Failed to deserialize JSON data.";
        LOG.error(msg, ex);
        throw new IllegalArgumentException(msg, ex);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JSONArray(org.jose4j.json.internal.json_simple.JSONArray) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URLConnection(java.net.URLConnection) URL(java.net.URL) Proxy(java.net.Proxy) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) JSONParser(org.jose4j.json.internal.json_simple.parser.JSONParser) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) InvalidUpdateDefinition(org.openecard.common.util.InvalidUpdateDefinition) ParseException(org.jose4j.json.internal.json_simple.parser.ParseException)

Aggregations

URL (java.net.URL)3 JSONObject (org.jose4j.json.internal.json_simple.JSONObject)3 JSONParser (org.jose4j.json.internal.json_simple.parser.JSONParser)3 IOException (java.io.IOException)2 Scanner (java.util.Scanner)2 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)2 ParseException (org.jose4j.json.internal.json_simple.parser.ParseException)2 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 Reader (java.io.Reader)1 Proxy (java.net.Proxy)1 URISyntaxException (java.net.URISyntaxException)1 URLConnection (java.net.URLConnection)1 ArrayList (java.util.ArrayList)1 JSONArray (org.jose4j.json.internal.json_simple.JSONArray)1 InvalidUpdateDefinition (org.openecard.common.util.InvalidUpdateDefinition)1