Java Code Examples for org.keycloak.util.JsonSerialization#writeValueAsString()

The following examples show how to use org.keycloak.util.JsonSerialization#writeValueAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenWithoutResourceAccess() throws Exception {
    AccessToken token = new AccessToken();
    token.id("111");
    token.issuer("http://localhost:8080/auth/acme");

    String json = JsonSerialization.writeValueAsString(token);

    // Assert JSON doesn't contain "realm_access" or "resource_access" fields as it doesn't have any roles specified
    Assert.assertFalse(json.contains("realm_access"));
    Assert.assertFalse(json.contains("resource_access"));

    token = JsonSerialization.readValue(json, AccessToken.class);

    Assert.assertNull(token.getRealmAccess());
    Assert.assertTrue(token.getResourceAccess() != null && token.getResourceAccess().isEmpty());
    Assert.assertNull(token.getResourceAccess("foo"));
}
 
Example 2
Source File: JSONUtil.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
/**
 * Convert object to JsonNode
 *
 * @param value Json-serializable object
 * @return Object as JsonNode
 */
public static JsonNode asJson(Object value) {
    if (value instanceof JsonNode)
        return (JsonNode) value;

    // We re-serialise and deserialize into generic json object
    try {
        String jsonString = JsonSerialization.writeValueAsString(value);
        return JsonSerialization.readValue(jsonString, JsonNode.class);
    } catch (IOException e) {
        throw new RuntimeException("Failed to convert value to JSON (" + value + ")", e);
    }
}
 
Example 3
Source File: PersistentUserSessionAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public PersistentUserSessionModel getUpdatedModel() {
    try {
        String updatedData = JsonSerialization.writeValueAsString(getData());
        this.model.setData(updatedData);
    } catch (IOException ioe) {
        throw new ModelException(ioe);
    }

    return this.model;
}
 
Example 4
Source File: PersistentAuthenticatedClientSessionAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public PersistentClientSessionModel getUpdatedModel() {
    try {
        String updatedData = JsonSerialization.writeValueAsString(getData());
        this.model.setData(updatedData);
    } catch (IOException ioe) {
        throw new ModelException(ioe);
    }

    return this.model;
}
 
Example 5
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void processClaimsQueryParam() throws IOException {
    Map<String, Object> claims = ImmutableMap.of(
            "id_token", ImmutableMap.of(
                    "test_claim", ImmutableMap.of(
                            "essential", true)));

    String claimsJson = JsonSerialization.writeValueAsString(claims);

    driver.navigate().to(oauth.getLoginFormUrl() + "&" + OIDCLoginProtocol.CLAIMS_PARAM + "=" + claimsJson);
    
    // need to login so session id can be read from event
    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    String sessionId = loginEvent.getSessionId();
    String clientId = loginEvent.getClientId();
    
    testingClient.server("test").run(session -> {
        RealmModel realmModel = session.getContext().getRealm();
        String clientUuid = realmModel.getClientByClientId(clientId).getId();
        UserSessionModel userSession = session.sessions().getUserSession(realmModel, sessionId);
        AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().get(clientUuid);
        
        String claimsInSession = clientSession.getNote(OIDCLoginProtocol.CLAIMS_PARAM);
        assertEquals(claimsJson, claimsInSession);
    });
}
 
Example 6
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void processClaimsRequestParam() throws Exception {
    Map<String, Object> claims = ImmutableMap.of(
            "id_token", ImmutableMap.of(
                    "test_claim", ImmutableMap.of(
                            "essential", true)));
    
    String claimsJson = JsonSerialization.writeValueAsString(claims);

    Map<String, Object> oidcRequest = new HashMap<>();
    oidcRequest.put(OIDCLoginProtocol.CLIENT_ID_PARAM, "test-app");
    oidcRequest.put(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
    oidcRequest.put(OIDCLoginProtocol.REDIRECT_URI_PARAM, oauth.getRedirectUri());
    oidcRequest.put(OIDCLoginProtocol.CLAIMS_PARAM, claims);

    String request = new JWSBuilder().jsonContent(oidcRequest).none();
    
    driver.navigate().to(oauth.getLoginFormUrl() + "&" + OIDCLoginProtocol.REQUEST_PARAM + "=" + request);
    
    // need to login so session id can be read from event
    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    String sessionId = loginEvent.getSessionId();
    String clientId = loginEvent.getClientId();
    
    testingClient.server("test").run(session -> {
        RealmModel realmModel = session.getContext().getRealm();
        String clientUuid = realmModel.getClientByClientId(clientId).getId();
        UserSessionModel userSession = session.sessions().getUserSession(realmModel, sessionId);
        AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(clientUuid);
        
        String claimsInSession = clientSession.getNote(OIDCLoginProtocol.CLAIMS_PARAM);
        assertEquals(claimsJson, claimsInSession);
    });
}
 
Example 7
Source File: CredentialModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void writeMapAsJson(Map<String, Object> map, boolean secret) {
    try {
        String jsonStr = JsonSerialization.writeValueAsString(map);
        if (secret) {
            this.secretData = jsonStr;
        } else {
            this.credentialData = jsonStr;
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 8
Source File: SerializedBrokeredIdentityContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void saveToAuthenticationSession(AuthenticationSessionModel authSession, String noteKey) {
    try {
        String asString = JsonSerialization.writeValueAsString(this);
        authSession.setAuthNote(noteKey, asString);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 9
Source File: ExistingUserInfo.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String serialize() {
    try {
        return JsonSerialization.writeValueAsString(this);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response redirectToAccountErrorPage(AuthenticationSessionModel authSession, String message, Object ... parameters) {
    fireErrorEvent(message);

    FormMessage errorMessage = new FormMessage(message, parameters);
    try {
        String serializedError = JsonSerialization.writeValueAsString(errorMessage);
        authSession.setAuthNote(AccountFormService.ACCOUNT_MGMT_FORWARDED_ERROR_NOTE, serializedError);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    URI accountServiceUri = UriBuilder.fromUri(authSession.getRedirectUri()).queryParam(Constants.TAB_ID, authSession.getTabId()).build();
    return Response.status(302).location(accountServiceUri).build();
}
 
Example 11
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void processResponse(KeycloakInstalled installed, String client) throws IOException {
    AccessTokenResponse tokenResponse = installed.getTokenResponse();
    tokenResponse.setExpiresIn(Time.currentTime() + tokenResponse.getExpiresIn());
    tokenResponse.setIdToken(null);
    String json = JsonSerialization.writeValueAsString(tokenResponse);
    getTokenDirectory().mkdirs();
    writeFile(getTokenFilePath(client), json);
}
 
Example 12
Source File: JWKTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void publicRs256() throws Exception {
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    X509Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, "Test");

    JWK jwk = JWKBuilder.create().kid(KeyUtils.createKeyId(publicKey)).algorithm("RS256").rsa(publicKey, certificate);

    assertNotNull(jwk.getKeyId());
    assertEquals("RSA", jwk.getKeyType());
    assertEquals("RS256", jwk.getAlgorithm());
    assertEquals("sig", jwk.getPublicKeyUse());

    assertTrue(jwk instanceof RSAPublicJWK);
    assertNotNull(((RSAPublicJWK) jwk).getModulus());
    assertNotNull(((RSAPublicJWK) jwk).getPublicExponent());
    assertNotNull(((RSAPublicJWK) jwk).getX509CertificateChain());
    assertEquals(PemUtils.encodeCertificate(certificate), ((RSAPublicJWK) jwk).getX509CertificateChain()[0]);
    assertNotNull(((RSAPublicJWK) jwk).getSha1x509Thumbprint());
    assertEquals(PemUtils.generateThumbprint(((RSAPublicJWK) jwk).getX509CertificateChain(), "SHA-1"), ((RSAPublicJWK) jwk).getSha1x509Thumbprint());
    assertNotNull(((RSAPublicJWK) jwk).getSha256x509Thumbprint());
    assertEquals(PemUtils.generateThumbprint(((RSAPublicJWK) jwk).getX509CertificateChain(), "SHA-256"), ((RSAPublicJWK) jwk).getSha256x509Thumbprint());

    String jwkJson = JsonSerialization.writeValueAsString(jwk);

    PublicKey publicKeyFromJwk = JWKParser.create().parse(jwkJson).toPublicKey();

    // Parse
    assertArrayEquals(publicKey.getEncoded(), publicKeyFromJwk.getEncoded());

    byte[] data = "Some test string".getBytes(StandardCharsets.UTF_8);
    byte[] sign = sign(data, JavaAlgorithm.RS256, keyPair.getPrivate());
    verify(data, sign, JavaAlgorithm.RS256, publicKeyFromJwk);
}
 
Example 13
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testToken() throws Exception {
    AccessToken token = createSimpleToken();

    String json = JsonSerialization.writeValueAsString(token);
    token = JsonSerialization.readValue(json, AccessToken.class);
    Assert.assertEquals("111", token.getId());
    AccessToken.Access foo = token.getResourceAccess("foo");
    Assert.assertNotNull(foo);
    Assert.assertTrue(foo.isUserInRole("admin"));

}
 
Example 14
Source File: SimpleHttp.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private StringEntity getJsonEntity() throws IOException {
    return new StringEntity(JsonSerialization.writeValueAsString(entity));
}
 
Example 15
Source File: JWKTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void publicEs256() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
    keyGen.initialize(ecSpec, randomGen);
    KeyPair keyPair = keyGen.generateKeyPair();

    PublicKey publicKey = keyPair.getPublic();

    JWK jwk = JWKBuilder.create().kid(KeyUtils.createKeyId(keyPair.getPublic())).algorithm("ES256").ec(publicKey);

    assertEquals("EC", jwk.getKeyType());
    assertEquals("ES256", jwk.getAlgorithm());
    assertEquals("sig", jwk.getPublicKeyUse());

    assertTrue(jwk instanceof ECPublicJWK);

    ECPublicJWK ecJwk = (ECPublicJWK) jwk;

    assertNotNull(ecJwk.getCrv());
    assertNotNull(ecJwk.getX());
    assertNotNull(ecJwk.getY());

    byte[] xBytes = Base64Url.decode(ecJwk.getX());
    byte[] yBytes = Base64Url.decode(ecJwk.getY());

    assertEquals(256/8, xBytes.length);
    assertEquals(256/8, yBytes.length);

    String jwkJson = JsonSerialization.writeValueAsString(jwk);

    JWKParser parser = JWKParser.create().parse(jwkJson);
    PublicKey publicKeyFromJwk = parser.toPublicKey();

    assertArrayEquals(publicKey.getEncoded(), publicKeyFromJwk.getEncoded());

    byte[] data = "Some test string".getBytes(StandardCharsets.UTF_8);
    byte[] sign = sign(data, JavaAlgorithm.ES256, keyPair.getPrivate());
    verify(data, sign, JavaAlgorithm.ES256, publicKeyFromJwk);
}
 
Example 16
Source File: JsonParserTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Map<String, Object> parseResourceRepresentation(String resourceJson) throws Exception {
    ResourceRepresentation rep = JsonSerialization.readValue(resourceJson, ResourceRepresentation.class);
    String repp = JsonSerialization.writeValueAsString(rep);
    return JsonSerialization.readValue(repp, Map.class);
}