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

The following examples show how to use org.keycloak.util.JsonSerialization#readValue() . 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: HttpAdapterUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static <T> T sendJsonHttpRequest(KeycloakDeployment deployment, HttpRequestBase httpRequest, Class<T> clazz) throws HttpClientAdapterException {
    try {
        HttpResponse response = deployment.getClient().execute(httpRequest);
        int status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            close(response);
            throw new HttpClientAdapterException("Unexpected status = " + status);
        }
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new HttpClientAdapterException("There was no entity.");
        }
        InputStream is = entity.getContent();
        try {
            return JsonSerialization.readValue(is, clazz);
        } finally {
            try {
                is.close();
            } catch (IOException ignored) {

            }
        }
    } catch (IOException e) {
        throw new HttpClientAdapterException("IO error", e);
    }
}
 
Example 2
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 6 votes vote down vote up
protected boolean validateRecaptcha(AuthenticationFlowContext context, boolean success, String captcha, String secret) {
	HttpClient httpClient = context.getSession().getProvider(HttpClientProvider.class).getHttpClient();
	HttpPost post = new HttpPost("https://www.google.com/recaptcha/api/siteverify");
	List<NameValuePair> formparams = new LinkedList<>();
	formparams.add(new BasicNameValuePair("secret", secret));
	formparams.add(new BasicNameValuePair("response", captcha));
	formparams.add(new BasicNameValuePair("remoteip", context.getConnection().getRemoteAddr()));
	try {
		UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
		post.setEntity(form);
		HttpResponse response = httpClient.execute(post);
		InputStream content = response.getEntity().getContent();
		try {
			Map json = JsonSerialization.readValue(content, Map.class);
			Object val = json.get("success");
			success = Boolean.TRUE.equals(val);
		} finally {
			content.close();
		}
	} catch (Exception e) {
		ServicesLogger.LOGGER.recaptchaFailed(e);
	}
	return success;
}
 
Example 3
Source File: TokenIntrospectionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntrospectAccessTokenUserDisabled() throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");

    EventRepresentation loginEvent = events.expectLogin().assertEvent();

    UserRepresentation userRep = new UserRepresentation();
    try {
        userRep.setEnabled(false);
        adminClient.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);

        String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
        TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);

        assertFalse(rep.isActive());
        assertNull(rep.getUserName());
        assertNull(rep.getClientId());
        assertNull(rep.getSubject());
    } finally {
        userRep.setEnabled(true);
        adminClient.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
    }
}
 
Example 4
Source File: AbstractAdminTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static <T> T loadJson(InputStream is, Class<T> type) {
    try {
        return JsonSerialization.readValue(is, type);
    } catch (IOException e) {
        throw new RuntimeException("Failed to parse json", e);
    }
}
 
Example 5
Source File: TokenRevocationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void isTokenEnabled(AccessTokenResponse tokenResponse, String clientId) throws IOException {
    String introspectionResponse = oauth.introspectAccessTokenWithClientCredential(clientId, "password",
        tokenResponse.getAccessToken());
    TokenMetadataRepresentation rep = JsonSerialization.readValue(introspectionResponse, TokenMetadataRepresentation.class);
    assertTrue(rep.isActive());

    oauth.clientId(clientId);
    OAuthClient.AccessTokenResponse tokenRefreshResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(),
        "password");
    assertEquals(Status.OK.getStatusCode(), tokenRefreshResponse.getStatusCode());
}
 
Example 6
Source File: DeviceActivityManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/** Returns the device information associated with the given {@code userSession}.
 * 
 * 
 * @param userSession the userSession
 * @return the device information or null if no device is attached to the user session
 */
public static DeviceRepresentation getCurrentDevice(UserSessionModel userSession) {
    String deviceInfo = userSession.getNote(DEVICE_NOTE);

    if (deviceInfo == null) {
        return null;
    }

    try {
        return JsonSerialization.readValue(Base64.decode(deviceInfo), DeviceRepresentation.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: PolicyService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AbstractPolicyRepresentation doCreateRepresentation(String payload) {
    PolicyRepresentation representation;

    try {
        representation = JsonSerialization.readValue(payload, PolicyRepresentation.class);
    } catch (IOException cause) {
        throw new RuntimeException("Failed to deserialize representation", cause);
    }

    return representation;
}
 
Example 8
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String readToken(String client) throws Exception {
    String json = getTokenResponse(client);
    if (json == null) return null;


    if (json != null) {
        try {
            AccessTokenResponse tokenResponse = JsonSerialization.readValue(json, AccessTokenResponse.class);
            if (Time.currentTime() < tokenResponse.getExpiresIn()) {
                return tokenResponse.getToken();
            }
            AdapterConfig config = getConfig();
            KeycloakInstalled installed = new KeycloakInstalled(KeycloakDeploymentBuilder.build(config));
            installed.refreshToken(tokenResponse.getRefreshToken());
            processResponse(installed, client);
            return tokenResponse.getToken();
        } catch (Exception e) {
            File tokenFile = getTokenFilePath(client);
            if (tokenFile.exists()) {
                tokenFile.delete();
            }

            return null;
        }
    }
    return null;

}
 
Example 9
Source File: AccountLinkSpringBootTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String getToken(OAuthClient.AccessTokenResponse response, Client httpClient) throws Exception {
    log.info("target here is " + OAuthClient.AUTH_SERVER_ROOT);
    String idpToken =  httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
            .path("realms")
            .path(REALM_NAME)
            .path("broker")
            .path(PARENT_REALM)
            .path("token")
            .request()
            .header("Authorization", "Bearer " + response.getAccessToken())
            .get(String.class);
    AccessTokenResponse res = JsonSerialization.readValue(idpToken, AccessTokenResponse.class);
    return res.getToken();
}
 
Example 10
Source File: TokenRevocationCorsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void isTokenDisabled(AccessTokenResponse tokenResponse, String clientId) throws IOException {
    String introspectionResponse = oauth.introspectAccessTokenWithClientCredential(clientId, "password",
        tokenResponse.getAccessToken());
    TokenMetadataRepresentation rep = JsonSerialization.readValue(introspectionResponse, TokenMetadataRepresentation.class);
    assertFalse(rep.isActive());

    oauth.clientId(clientId);
    OAuthClient.AccessTokenResponse tokenRefreshResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(),
        "password");
    assertEquals(Status.BAD_REQUEST.getStatusCode(), tokenRefreshResponse.getStatusCode());
}
 
Example 11
Source File: OIDCWellKnownProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntrospectionEndpointClaim() throws IOException {
    Client client = ClientBuilder.newClient();
    try {
        ObjectNode oidcConfig = JsonSerialization.readValue(getOIDCDiscoveryConfiguration(client), ObjectNode.class);
        assertEquals(oidcConfig.get("introspection_endpoint").asText(), getOIDCDiscoveryRepresentation(client).getTokenIntrospectionEndpoint());
    } finally {
        client.close();
    }
}
 
Example 12
Source File: ClientRegistration.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static <T> T deserialize(InputStream inputStream, Class<T> clazz) throws ClientRegistrationException {
    try {
        return JsonSerialization.readValue(inputStream, clazz);
    } catch (IOException e) {
        throw new ClientRegistrationException("Failed to read json object", e);
    }
}
 
Example 13
Source File: HttpUtil.java    From pnc with Apache License 2.0 5 votes vote down vote up
private static InputStream doRequest(String authorization, HttpRequestBase request) throws IOException {
    addAuth(request, authorization);

    HttpResponse response = getHttpClient().execute(request);
    InputStream responseStream = null;
    if (response.getEntity() != null) {
        responseStream = response.getEntity().getContent();
    }

    int code = response.getStatusLine().getStatusCode();
    if (code >= 200 && code < 300) {
        return responseStream;
    } else {
        Map<String, String> error = null;
        try {
            org.apache.http.Header header = response.getEntity().getContentType();
            if (header != null && APPLICATION_JSON.equals(header.getValue())) {
                error = JsonSerialization.readValue(responseStream, Map.class);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to read error response - " + e.getMessage(), e);
        } finally {
            responseStream.close();
        }

        String message = null;
        if (error != null) {
            message = error.get("error_description") + " [" + error.get("error") + "]";
        }
        throw new RuntimeException(
                message != null ? message
                        : response.getStatusLine().getStatusCode() + " "
                                + response.getStatusLine().getReasonPhrase());
    }
}
 
Example 14
Source File: DirectAccessGrantsLoginModule.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public boolean logout() throws LoginException {
    if (refreshToken != null) {
        try {
            URI logoutUri = deployment.getLogoutUrl().clone().build();
            HttpPost post = new HttpPost(logoutUri);

            List<NameValuePair> formparams = new ArrayList<>();
            ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
            formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));

            UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(form);

            HttpClient client = deployment.getClient();
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (status != 204) {
                StringBuilder errorBuilder = new StringBuilder("Logout of refreshToken failed. Invalid status: " + status);
                if (entity != null) {
                    InputStream is = entity.getContent();
                    if (status == 400) {
                        OAuth2ErrorRepresentation errorRep = JsonSerialization.readValue(is, OAuth2ErrorRepresentation.class);
                        errorBuilder.append(", OAuth2 error. Error: " + errorRep.getError())
                                .append(", Error description: " + errorRep.getErrorDescription());

                    } else {
                        if (is != null) is.close();
                    }
                }

                // Should do something better than warn if logout failed? Perhaps update of refresh tokens on existing subject might be supported too...
                log.warn(errorBuilder.toString());
            }
        } catch (IOException ioe) {
            log.warn(ioe);
        }
    }

    return super.logout();
}
 
Example 15
Source File: ClientRegistrationPoliciesTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void assertRegAccessToken(String registrationAccessToken, RegistrationAuth expectedRegAuth) throws Exception {
    byte[] content = new JWSInput(registrationAccessToken).getContent();
    RegistrationAccessToken regAccessToken = JsonSerialization.readValue(content, RegistrationAccessToken.class);
    Assert.assertEquals(regAccessToken.getRegistrationAuth(), expectedRegAuth.toString().toLowerCase());
}
 
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);
}
 
Example 17
Source File: AddUserTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void addUserTest() throws Exception {
    final String username = "addusertest-admin";
    final String realmName = "master";
    final String configDir = System.getProperty("auth.server.config.dir");
    assertThat("AuthServer config directory is NULL !!", configDir, notNullValue());

    String authServerQualifier = suiteContext.getAuthServerInfo().getQualifier();
    assertThat("Qualifier of AuthServer is empty or NULL !!", authServerQualifier, not(isEmptyOrNullString()));
    assertThat("Controller isn't running.", controller.isStarted(authServerQualifier), is(true));

    AddUser.main(new String[]{"-u", username, "-p", "password", "--sc", configDir});

    //Read keycloak-add-user.json
    List<RealmRepresentation> realms = JsonSerialization.readValue(new FileInputStream(new File(configDir, "keycloak-add-user.json")),
            new TypeReference<List<RealmRepresentation>>() {
            });

    assertThat("File 'keycloak-add-user.json' is empty.", realms, not(empty()));

    //-----------------Get-Indexes-------------------//
    int realmIndex = getRealmIndex(realmName, realms);
    assertThat("Realm " + realmName + " not found.", realmIndex, is(not(-1)));

    int userIndex = getUserIndex(username, realms.get(realmIndex).getUsers());
    assertThat("User " + username + " not found", userIndex, is(not(-1)));


    UserRepresentation user = realms.get(realmIndex).getUsers().get(userIndex);
    assertThat("Username from Json file is wrong.", user.getUsername(), is(username));

    //------------------Credentials-----------------------------//
    assertThat("User Credentials are NULL", user.getCredentials().get(0), notNullValue());
    CredentialRepresentation credentials = user.getCredentials().get(0);
    PasswordCredentialModel pcm = PasswordCredentialModel.createFromCredentialModel(RepresentationToModel.toModel(credentials));
    assertThat("User Credentials have wrong Algorithm.", pcm.getPasswordCredentialData().getAlgorithm(), is(Pbkdf2Sha256PasswordHashProviderFactory.ID));
    assertThat("User Credentials have wrong Hash Iterations", pcm.getPasswordCredentialData().getHashIterations(), is(100000));

    //------------------Restart--Container---------------------//
    controller.stop(authServerQualifier);
    controller.start(authServerQualifier);

    RealmResource realmResource = getAdminClient().realm(realmName);
    assertThat("Realm resource is NULL !!", realmResource, notNullValue());

    user = realmResource.users().search(username).get(0);
    assertThat("Username is wrong.", user.getUsername(), is(username));

    UserResource userResource = realmResource.users().get(user.getId());
    assertThat("User resource is NULL !!", userResource, notNullValue());

    //--------------Roles-----------------------//
    try {
        List<RoleRepresentation> realmRoles = userResource.roles().realmLevel().listAll();

        assertRoles(realmRoles, "admin", "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION);

        List<ClientRepresentation> clients = realmResource.clients().findAll();
        String accountId = null;
        for (ClientRepresentation c : clients) {
            if (c.getClientId().equals("account")) {
                accountId = c.getId();
            }
        }

        List<RoleRepresentation> accountRoles = userResource.roles().clientLevel(accountId).listAll();
        assertRoles(accountRoles, "view-profile", "manage-account");
    } finally {
        userResource.remove();
    }
}
 
Example 18
Source File: SimpleHttp.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public <T> T asJson(Class<T> type) throws IOException {
    if (headers == null || !headers.containsKey("Accept")) {
        header("Accept", "application/json");
    }
    return JsonSerialization.readValue(asString(), type);
}
 
Example 19
Source File: KcAdmTest.java    From keycloak with Apache License 2.0 2 votes vote down vote up
@Test
public void testCustomConfigLoginCreateDelete() throws IOException {
    /*
     *  Test user login, create, delete session using a custom config file
     */

    // prepare for loading a config file
    FileConfigHandler handler = initCustomConfigFile();

    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {

        KcAdmExec exe = KcAdmExec.execute("config credentials --server " + serverUrl +
                " --realm master --user admin --password admin --config '" + configFile.getName() + "'");

        assertExitCodeAndStreamSizes(exe, 0, 0, 1);

        // remember the state of config file
        ConfigData config1 = handler.loadConfig();




        exe = KcAdmExec.execute("create --config '" + configFile.getName() + "' clients -s clientId=test-client -o");

        assertExitCodeAndStdErrSize(exe, 0, 0);

        // check changes to config file
        ConfigData config2 = handler.loadConfig();
        assertFieldsEqualWithExclusions(config1, config2);


        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client.getClientId());



        exe = KcAdmExec.execute("delete clients/" + client.getId() + " --config '" + configFile.getName() + "'");

        assertExitCodeAndStreamSizes(exe, 0, 0, 0);

        // check changes to config file
        ConfigData config3 = handler.loadConfig();
        assertFieldsEqualWithExclusions(config2, config3);
    }
}
 
Example 20
Source File: AbstractAdmCliTest.java    From keycloak with Apache License 2.0 2 votes vote down vote up
void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extraOptions, String loginMessage) throws IOException {

        File configFile = getDefaultConfigFilePath();
        long lastModified = configFile.exists() ? configFile.lastModified() : 0;

        // This test assumes it is the only user of any instance of on the system
        KcAdmExec exe = execute("create clients --no-config --server " + serverUrl +
                " --realm test " + credentials + " " + extraOptions + " -s clientId=test-client -o");

        Assert.assertEquals("exitCode == 0", 0, exe.exitCode());
        Assert.assertEquals("login message", loginMessage, exe.stderrLines().get(0));

        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client.getClientId());

        long lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        exe = execute("get clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions);

        assertExitCodeAndStdErrSize(exe, 0, 1);

        ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client2.getClientId());

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        exe = execute("update clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " +
                credentials + " " + extraOptions + " -s enabled=false -o");

        assertExitCodeAndStdErrSize(exe, 0, 1);

        ClientRepresentation client4 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client4.getClientId());
        Assert.assertFalse("enabled", client4.isEnabled());

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        exe = execute("delete clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions);

        int linecountOffset = "".equals(loginMessage) ? 1 : 0; // if there is no login, then there is one less stdErrLinecount
        assertExitCodeAndStreamSizes(exe, 0, 0, 1 - linecountOffset);

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        // subsequent delete should fail
        exe = execute("delete clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions);

        assertExitCodeAndStreamSizes(exe, 1, 0, 2 - linecountOffset);
        String resourceUri = serverUrl + "/admin/realms/test/clients/" + client.getId();
        Assert.assertEquals("error message", "Resource not found for url: " + resourceUri, exe.stderrLines().get(1 - linecountOffset));

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);
    }