use of org.jose4j.json.internal.json_simple.JSONObject in project java by kubernetes-client.
the class OpenIDConnectAuthenticationTest method testRefreshUnauthorized.
@Test(expected = RuntimeException.class)
public void testRefreshUnauthorized() throws Exception {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(OIDC_KS_PATH), OIDC_KS_PASSWORD);
String refreshedJWT = TestUtils.generateJWT("someuser", "https://localhost:" + PORT, (PrivateKey) ks.getKey("oidc-sig", OIDC_KS_PASSWORD), TestUtils.DateOptions.Now);
stubFor(get("/.well-known/openid-configuration").willReturn(aResponse().withStatus(200).withBody("{\"issuer\":\"https://localhost:8043\",\"authorization_endpoint\":\"https://localhost:8043/auth\",\"token_endpoint\":\"https://localhost:8043/token\",\"userinfo_endpoint\":\"https://localhost:8043/userinfo\",\"revocation_endpoint\":\"https://localhost:8043/revoke\",\"jwks_uri\":\"https://localhost:8043/certs\",\"response_types_supported\":[\"code\",\"token\",\"id_token\",\"code token\",\"code id_token\",\"token id_token\",\"code token id_token\",\"none\"],\"subject_types_supported\":[\"public\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"scopes_supported\":[\"openid\",\"email\",\"profile\"],\"token_endpoint_auth_methods_supported\":[\"client_secret_post\"],\"claims_supported\":[\"sub\",\"aud\",\"iss\",\"exp\",\"sub\",\"name\",\"groups\",\"preferred_username\",\"email\"],\"code_challenge_methods_supported\":[\"plain\",\"S256\"]}")));
JSONObject respToken = new JSONObject();
respToken.put("id_token", refreshedJWT);
respToken.put("refresh_token", "new_refresh_token");
stubFor(post("/token").willReturn(aResponse().withStatus(401)));
OpenIDConnectAuthenticator oidcAuth = new OpenIDConnectAuthenticator();
Map<String, Object> config = new HashMap<String, Object>();
KeyStore serverKs = KeyStore.getInstance("JKS");
serverKs.load(new FileInputStream(OIDC_SERVER_KS_PATH), OIDC_KS_PASSWORD);
String jwt = TestUtils.generateJWT("someuser", "https://localhost:" + PORT, (PrivateKey) ks.getKey("oidc-sig", OIDC_KS_PASSWORD), TestUtils.DateOptions.Past);
config.put(OpenIDConnectAuthenticator.OIDC_ID_TOKEN, jwt);
config.put(OpenIDConnectAuthenticator.OIDC_ISSUER, "https://localhost:" + PORT);
config.put(OpenIDConnectAuthenticator.OIDC_CLIENT_ID, "kubernetes");
config.put(OpenIDConnectAuthenticator.OIDC_REFRESH_TOKEN, "refresh-me-please");
config.put(OpenIDConnectAuthenticator.OIDC_IDP_CERT_DATA, Base64.encodeBase64String(exportCert((X509Certificate) serverKs.getCertificate("mykey")).getBytes(StandardCharsets.UTF_8)));
Map<String, Object> respMap = oidcAuth.refresh(config);
}
use of org.jose4j.json.internal.json_simple.JSONObject in project java by kubernetes-client.
the class OpenIDConnectAuthenticator method refresh.
@Override
public Map<String, Object> refresh(Map<String, Object> config) {
String issuer = (String) config.get(OIDC_ISSUER);
String clientId = (String) config.get(OIDC_CLIENT_ID);
String refreshToken = (String) config.get(OIDC_REFRESH_TOKEN);
String clientSecret = (String) config.getOrDefault(OIDC_CLIENT_SECRET, "");
String idpCert = (String) config.get(OIDC_IDP_CERT_DATA);
SSLContext sslContext = null;
if (idpCert != null) {
// fist, lets get the pem
String pemCert = new String(Base64.getDecoder().decode(idpCert));
// next lets get a cert object
// need an alias name to store the certificate in a keystore. Also
// java keystores need passwords. this value is as good as any as
// there isn't anything actually secret being stored.
String alias = "doenotmatter";
KeyStore ks;
try {
ks = java.security.KeyStore.getInstance("PKCS12");
ks.load(null, alias.toCharArray());
ByteArrayInputStream bais = new ByteArrayInputStream(pemCert.getBytes(StandardCharsets.UTF_8));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection<? extends java.security.cert.Certificate> c = cf.generateCertificates(bais);
int j = 0;
for (java.security.cert.Certificate certificate : c) {
ks.setCertificateEntry(alias + "-" + j, certificate);
j++;
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
// TODO would be good to make this more dyanamic. Doesn't seem like
// a good way to do this.
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | KeyManagementException e) {
throw new RuntimeException("Could not import idp certificate", e);
}
}
// check the identity provider's configuration url for a token endpoint
String tokenURL = loadTokenURL(issuer, sslContext);
// get the refreshed tokens
JSONObject response = refreshOidcToken(clientId, refreshToken, clientSecret, sslContext, tokenURL);
// reload the config
config.put(OIDC_ID_TOKEN, response.get("id_token"));
config.put(OIDC_REFRESH_TOKEN, response.get("refresh_token"));
return config;
}
use of org.jose4j.json.internal.json_simple.JSONObject 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);
}
}
use of org.jose4j.json.internal.json_simple.JSONObject 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);
}
}
use of org.jose4j.json.internal.json_simple.JSONObject in project service-proxy by membrane.
the class GenericJsonParser method parse.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T parse(Class<T> clazz, JSONObject json) {
T obj = null;
try {
obj = clazz.newInstance();
for (Object property : json.entrySet()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) property;
Method setter = getSetter(clazz, entry.getKey());
Object toSetValue = entry.getValue();
if (isStructured(setter)) {
if (isCollection(setter)) {
JSONArray collection = new JSONArray((Collection) toSetValue);
List<Object> coll = new ArrayList<>();
for (Object o : collection) {
JSONObject jo = new JSONObject((Map) o);
String key = (String) jo.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Can't get key from " + jo));
JSONObject unwrapped = new JSONObject((Map<String, Object>) jo.get(key));
Class<?> child = K8sHelperGeneratorAutoGenerated.elementMapping.get(key);
coll.add(parse(child, unwrapped));
}
toSetValue = coll;
} else {
Class<?> childClass = K8sHelperGeneratorAutoGenerated.elementMapping.get(entry.getKey());
toSetValue = parse(childClass, new JSONObject((Map) json.get(entry.getKey())));
}
}
setSetter(obj, setter, toSetValue);
}
} catch (Throwable e) {
e.printStackTrace();
}
return obj;
}
Aggregations