org.keycloak.util.JsonSerialization Java Examples

The following examples show how to use org.keycloak.util.JsonSerialization. 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: KeycloakQuarkusConfiguration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void validate() throws ConfigurationException {
    int basePort = getBindHttpPort();
    int newPort = basePort + bindHttpPortOffset;
    setBindHttpPort(newPort);

    int baseHttpsPort = getBindHttpsPort();
    int newHttpsPort = baseHttpsPort + bindHttpsPortOffset;
    setBindHttpsPort(newHttpsPort);

    log.info("Keycloak will listen for http on port: " + newPort + " and for https on port: " + newHttpsPort);

    if (this.keycloakConfigPropertyOverrides != null) {
        try {
            TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
            this.keycloakConfigPropertyOverridesMap = JsonSerialization.sysPropertiesAwareMapper.readValue(this.keycloakConfigPropertyOverrides, typeRef);
        } catch (IOException ex) {
            throw new ConfigurationException(ex);
        }
    }
}
 
Example #2
Source File: JsonParserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnwrap() throws Exception {
    // just experimenting with unwrapped and any properties
    IDToken test = new IDToken();
    test.getOtherClaims().put("phone_number", "978-666-0000");
    test.getOtherClaims().put("email_verified", "true");
    test.getOtherClaims().put("yo", "true");
    Map<String, String> nested = new HashMap<String, String>();
    nested.put("foo", "bar");
    test.getOtherClaims().put("nested", nested);
    String json = JsonSerialization.writeValueAsPrettyString(test);
    System.out.println(json);

    test = JsonSerialization.readValue(json, IDToken.class);
    System.out.println("email_verified property: " + test.getEmailVerified());
    System.out.println("property: " + test.getPhoneNumber());
    System.out.println("map: " + test.getOtherClaims().get("phone_number"));
    Assert.assertNotNull(test.getPhoneNumber());
    Assert.assertNotNull(test.getOtherClaims().get("yo"));
    Assert.assertNull(test.getOtherClaims().get("phone_number"));
    nested = (Map<String, String>)test.getOtherClaims().get("nested");
    Assert.assertNotNull(nested);
    Assert.assertNotNull(nested.get("foo"));
}
 
Example #3
Source File: PolicyResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new user-managed permission as represented by the given {@code permission}.
 *
 * @param permission the permission to create
 * @return if successful, the permission created
 */
public UmaPermissionRepresentation create(final UmaPermissionRepresentation permission) {
    if (permission == null) {
        throw new IllegalArgumentException("Permission must not be null");
    }

    Callable<UmaPermissionRepresentation> callable = new Callable<UmaPermissionRepresentation>() {
        @Override
        public UmaPermissionRepresentation call() throws Exception {
            return http.<UmaPermissionRepresentation>post(serverConfiguration.getPolicyEndpoint() + "/" + resourceId)
                    .authorizationBearer(pat.call())
                    .json(JsonSerialization.writeValueAsBytes(permission))
                    .response().json(UmaPermissionRepresentation.class).execute();
        }
    };
    try {
        return callable.call();
    } catch (Exception cause) {
        return Throwables.retryAndWrapExceptionIfNecessary(callable, pat, "Error creating policy for resource [" + resourceId + "]", cause);
    }
}
 
Example #4
Source File: UncaughtErrorPageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@UncaughtServerErrorExpected
public void uncaughtErrorClientRegistration() throws IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpPost post = new HttpPost(suiteContext.getAuthServerInfo().getUriBuilder().path("/auth/realms/master/clients-registrations/openid-connect").build());
        post.setEntity(new StringEntity("{ invalid : invalid }"));
        post.setHeader("Content-Type", "application/json");

        CloseableHttpResponse response = client.execute(post);
        assertEquals(400, response.getStatusLine().getStatusCode());

        OAuth2ErrorRepresentation error = JsonSerialization.readValue(response.getEntity().getContent(), OAuth2ErrorRepresentation.class);
        assertEquals("unknown_error", error.getError());
        assertNull(error.getErrorDescription());
    }
}
 
Example #5
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> start() {
    for (String realmId : Arrays.asList("a", "b", "c", "d", "webapp", "webapp2")) {
        RealmRepresentation realm = createRealm(KEYCLOAK_REALM + realmId);

        realm.getClients().add(createClient("quarkus-app-" + realmId));
        realm.getUsers().add(createUser("alice", "user"));
        realm.getUsers().add(createUser("admin", "user", "admin"));
        realm.getUsers().add(createUser("jdoe", "user", "confidential"));

        try {
            RestAssured
                    .given()
                    .auth().oauth2(getAdminAccessToken())
                    .contentType("application/json")
                    .body(JsonSerialization.writeValueAsBytes(realm))
                    .when()
                    .post(KEYCLOAK_SERVER_URL + "/admin/realms").then()
                    .statusCode(201);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return Collections.emptyMap();
}
 
Example #6
Source File: PreAuthActionsHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void handlePushNotBefore()  {
    if (log.isTraceEnabled()) {
        log.trace("K_PUSH_NOT_BEFORE sent");
    }
    try {
        JWSInput token = verifyAdminRequest();
        if (token == null) {
            return;
        }
        PushNotBeforeAction action = JsonSerialization.readValue(token.getContent(), PushNotBeforeAction.class);
        if (!validateAction(action)) return;
        deployment.updateNotBefore(action.getNotBefore());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: KeycloakDevModeRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> start() {
    try {

        RealmRepresentation realm = createRealm(KEYCLOAK_REALM);

        realm.getClients().add(createClient("client-dev-mode"));
        realm.getUsers().add(createUser("alice-dev-mode", "user"));

        RestAssured
                .given()
                .auth().oauth2(getAdminAccessToken())
                .contentType("application/json")
                .body(JsonSerialization.writeValueAsBytes(realm))
                .when()
                .post(KEYCLOAK_SERVER_URL + "/admin/realms").then()
                .statusCode(201);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return Collections.emptyMap();
}
 
Example #8
Source File: PolicyTypeService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractPolicyRepresentation doCreateRepresentation(String payload) {
    PolicyProviderFactory provider = getPolicyProviderFactory(type);
    Class<? extends AbstractPolicyRepresentation> representationType = provider.getRepresentationType();

    if (representationType == null) {
        throw new RuntimeException("Policy provider for type [" + type + "] returned a null representation type.");
    }

    AbstractPolicyRepresentation representation;

    try {
        representation = JsonSerialization.readValue(payload, representationType);
    } catch (IOException e) {
        throw new RuntimeException("Failed to deserialize JSON using policy provider for type [" + type + "].", e);
    }

    representation.setType(type);

    return representation;
}
 
Example #9
Source File: AdminClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<RoleRepresentation> getRealmRoles(HttpServletRequest request, AccessTokenResponse res) throws Failure {

        HttpClient client = new DefaultHttpClient();
        try {
            HttpGet get = new HttpGet(UriUtils.getOrigin(request.getRequestURL().toString()) + "/auth/admin/realms/demo/roles");
            get.addHeader("Authorization", "Bearer " + res.getToken());
            try {
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new Failure(response.getStatusLine().getStatusCode());
                }
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                try {
                    return JsonSerialization.readValue(is, TypedList.class);
                } finally {
                    is.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
 
Example #10
Source File: ProductDatabaseClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<String> getProducts(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/database/products");
        get.addHeader("Authorization", "Bearer " + session.getTokenString());
        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Failure(response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, TypedList.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #11
Source File: DMRConfigProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Config.ConfigProvider> create() {

    ServletContext context = Resteasy.getContextData(ServletContext.class);

    JsonNode node = null;

    try {
        String dmrConfig = loadDmrConfig(context);
        if (dmrConfig != null) {
            node = JsonSerialization.mapper.readTree(dmrConfig);
            ServicesLogger.LOGGER.loadingFrom("standalone.xml or domain.xml");
        }
    } catch (IOException e) {
        LOG.warn("Failed to load DMR config", e);
    }

    return createJsonProvider(node);

}
 
Example #12
Source File: HeadersBodyStatus.java    From pnc with Apache License 2.0 6 votes vote down vote up
public void checkSuccess() {
    int code = getStatusCode();
    if (code < 200 || code >= 300) {
        String content = readBodyString();
        Map<String, String> error = null;
        try {
            error = JsonSerialization.readValue(content, Map.class);
        } catch (Exception ignored) {
        }

        String message = null;
        if (error != null) {
            String description = error.get("error_description");
            String err = error.get("error");
            String msg = error.get("errorMessage");
            message = msg != null ? msg : err != null ? (description + " [" + error.get("error") + "]") : null;
        }
        throw new HttpResponseException(getStatusCodeAndReason(), message, new RuntimeException(content));
    }
}
 
Example #13
Source File: DefaultDataMarshaller.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T deserialize(String serialized, Class<T> clazz) {
    try {
        if (clazz.equals(String.class)) {
            return clazz.cast(serialized);
        } else {
            byte[] bytes = Base64Url.decode(serialized);
            if (List.class.isAssignableFrom(clazz)) {
                List list = JsonSerialization.readValue(bytes, List.class);
                return clazz.cast(list);
            } else {
                return JsonSerialization.readValue(bytes, clazz);
            }
        }
    }  catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example #14
Source File: KeycloakOnUndertowConfiguration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void validate() throws ConfigurationException {
    super.validate();

    int basePort = getBindHttpPort();
    int newPort = basePort + bindHttpPortOffset;
    setBindHttpPort(newPort);

    int baseHttpsPort = getBindHttpsPort();
    int newHttpsPort = baseHttpsPort + bindHttpsPortOffset;
    setBindHttpsPort(newHttpsPort);

    log.info("KeycloakOnUndertow will listen for http on port: " + newPort + " and for https on port: " + newHttpsPort);
    
    if (this.keycloakConfigPropertyOverrides != null) {
        try {
            TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
            this.keycloakConfigPropertyOverridesMap = JsonSerialization.sysPropertiesAwareMapper.readValue(this.keycloakConfigPropertyOverrides, typeRef);
        } catch (IOException ex) {
            throw new ConfigurationException(ex);
        }
    }

    // TODO validate workerThreads
    
}
 
Example #15
Source File: RSAVerifierTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void testSpeed() throws Exception
{
    // Took 44 seconds with 50000 iterations
   byte[] tokenBytes = JsonSerialization.writeValueAsBytes(token);

   long start = System.currentTimeMillis();
   int count = 50000;
   for (int i = 0; i < count; i++)
   {
       String encoded = new JWSBuilder()
               .content(tokenBytes)
               .rsa256(idpPair.getPrivate());

       verifySkeletonKeyToken(encoded);

   }
   long end = System.currentTimeMillis() - start;
   System.out.println("took: " + end);
}
 
Example #16
Source File: AuthorizationAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void testResourceServerAsAudience(String clientId, String resourceServerClientId, String authzConfigFile) throws Exception {
    AuthzClient authzClient = getAuthzClient(authzConfigFile);
    PermissionRequest request = new PermissionRequest();

    request.setResourceId("Resource A");

    String accessToken = new OAuthClient().realm("authz-test").clientId(clientId).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
    String ticket = authzClient.protection().permission().create(request).getTicket();

    // Ticket is opaque to client or resourceServer. The audience should be just an authorization server itself
    JsonWebToken ticketDecoded = JsonSerialization.readValue(new JWSInput(ticket).getContent(), JsonWebToken.class);
    Assert.assertFalse(ticketDecoded.hasAudience(clientId));
    Assert.assertFalse(ticketDecoded.hasAudience(resourceServerClientId));

    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(new AuthorizationRequest(ticket));

    assertNotNull(response.getToken());
    AccessToken rpt = toAccessToken(response.getToken());
    assertEquals(resourceServerClientId, rpt.getAudience()[0]);
}
 
Example #17
Source File: AuthzEndpointRequestObjectParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AuthzEndpointRequestObjectParser(KeycloakSession session, String requestObject, ClientModel client) throws Exception {
    JWSInput input = new JWSInput(requestObject);
    JWSHeader header = input.getHeader();
    Algorithm headerAlgorithm = header.getAlgorithm();

    Algorithm requestedSignatureAlgorithm = OIDCAdvancedConfigWrapper.fromClientModel(client).getRequestObjectSignatureAlg();

    if (headerAlgorithm == null) {
        throw new RuntimeException("Request object signed algorithm not specified");
    }
    if (requestedSignatureAlgorithm != null && requestedSignatureAlgorithm != headerAlgorithm) {
        throw new RuntimeException("Request object signed with different algorithm than client requested algorithm");
    }

    if (header.getAlgorithm() == Algorithm.none) {
        this.requestParams = JsonSerialization.readValue(input.getContent(), JsonNode.class);
    } else {
        this.requestParams = session.tokens().decodeClientJWT(requestObject, client, JsonNode.class);
        if (this.requestParams == null) {
        	throw new RuntimeException("Failed to verify signature on 'request' object");
        }
    }
}
 
Example #18
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private AuthzClient getAuthzClient(String configFile) {
    if (authzClient == null) {
        Configuration configuration;
        try {
            configuration = JsonSerialization.readValue(httpsAwareConfigurationStream(getClass().getResourceAsStream("/authorization-test/" + configFile)), Configuration.class);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read configuration", e);
        }
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setValidateAfterInactivity(10);
        connectionManager.setMaxTotal(10);
        HttpClient client = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();
        authzClient = AuthzClient.create(new Configuration(configuration.getAuthServerUrl(), configuration.getRealm(), configuration.getResource(), configuration.getCredentials(), client));
    }

    return authzClient;
}
 
Example #19
Source File: JWSInput.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public JWSInput(String wire) throws JWSInputException {
    try {
        this.wireString = wire;
        String[] parts = wire.split("\\.");
        if (parts.length < 2 || parts.length > 3) throw new IllegalArgumentException("Parsing error");
        encodedHeader = parts[0];
        encodedContent = parts[1];
        encodedSignatureInput = encodedHeader + '.' + encodedContent;
        content = Base64Url.decode(encodedContent);
        if (parts.length > 2) {
            encodedSignature = parts[2];
            signature = Base64Url.decode(encodedSignature);

        }
        byte[] headerBytes = Base64Url.decode(encodedHeader);
        header = JsonSerialization.readValue(headerBytes, JWSHeader.class);
    } catch (Throwable t) {
        throw new JWSInputException(t);
    }
}
 
Example #20
Source File: UserManagedPermissionService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("{policyId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Response update(@PathParam("policyId") String policyId, String payload) {
    UmaPermissionRepresentation representation;

    try {
        representation = JsonSerialization.readValue(payload, UmaPermissionRepresentation.class);
    } catch (IOException e) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Failed to parse representation", Status.BAD_REQUEST);
    }

    checkRequest(getAssociatedResourceId(policyId), representation);

    return PolicyTypeResourceService.class.cast(delegate.getResource(policyId)).update(payload);
}
 
Example #21
Source File: KeycloakClientDescriptionConverter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ClientRepresentation convertToInternal(String description) {
    try {
        return JsonSerialization.readValue(description, ClientRepresentation.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: LinkAndExchangeServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessTokenResponse doTokenExchange(String realm, String token, String requestedIssuer,
                                           String clientId, String clientSecret) throws Exception {

    try (CloseableHttpClient client = (CloseableHttpClient) new HttpClientBuilder().disableTrustManager().build()) {
        String exchangeUrl = KeycloakUriBuilder.fromUri(ServletTestUtils.getAuthServerUrlBase())
                .path("/auth/realms/{realm}/protocol/openid-connect/token").build(realm).toString();

        HttpPost post = new HttpPost(exchangeUrl);
        HashMap<String, String> parameters = new HashMap<>();

        if (clientSecret != null) {
            String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
            post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
            post.setHeader(HttpHeaders.AUTHORIZATION, authorization);
        } else {
            parameters.put("client_id", clientId);
        }

        parameters.put(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE);
        parameters.put(OAuth2Constants.SUBJECT_TOKEN, token);
        parameters.put(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
        parameters.put(OAuth2Constants.REQUESTED_ISSUER, requestedIssuer);

        post.setEntity(new StringEntity(getPostDataString(parameters)));
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200 || statusCode == 400) {
            return JsonSerialization.readValue(EntityUtils.toString(response.getEntity()), AccessTokenResponse.class);
        } else {
            throw new RuntimeException("Unknown error!");
        }
    }
}
 
Example #23
Source File: CxfRsClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static List<String> getCustomers(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new HttpClientBuilder()
            .disableTrustManager().build();
    try {
        HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/cxf/customerservice/customers");
        get.addHeader("Authorization", "Bearer " + session.getTokenString());
        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Failure(response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, TypedList.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #24
Source File: RolePolicyProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public RolePolicyRepresentation toRepresentation(Policy policy, AuthorizationProvider authorization) {
    RolePolicyRepresentation representation = new RolePolicyRepresentation();

    try {
        representation.setRoles(new HashSet<>(Arrays.asList(JsonSerialization.readValue(policy.getConfig().get("roles"), RolePolicyRepresentation.RoleDefinition[].class))));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to deserialize roles", cause);
    }

    return representation;
}
 
Example #25
Source File: IOUtil.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 load json.", e);
    }
}
 
Example #26
Source File: UserPolicyProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void postInit(KeycloakSessionFactory factory) {
    factory.register(event -> {
        if (event instanceof UserRemovedEvent) {
            KeycloakSession keycloakSession = ((UserRemovedEvent) event).getKeycloakSession();
            AuthorizationProvider provider = keycloakSession.getProvider(AuthorizationProvider.class);
            StoreFactory storeFactory = provider.getStoreFactory();
            PolicyStore policyStore = storeFactory.getPolicyStore();
            UserModel removedUser = ((UserRemovedEvent) event).getUser();
            RealmModel realm = ((UserRemovedEvent) event).getRealm();
            ResourceServerStore resourceServerStore = storeFactory.getResourceServerStore();
            realm.getClients().forEach(clientModel -> {
                ResourceServer resourceServer = resourceServerStore.findById(clientModel.getId());

                if (resourceServer != null) {
                    policyStore.findByType(getId(), resourceServer.getId()).forEach(policy -> {
                        List<String> users = new ArrayList<>();

                        for (String userId : getUsers(policy)) {
                            if (!userId.equals(removedUser.getId())) {
                                users.add(userId);
                            }
                        }

                        try {
                            // just update the policy, let the UserSynchronizer to actually remove the policy if necessary
                            if (!users.isEmpty()) {
                                policy.putConfig("users", JsonSerialization.writeValueAsString(users));
                            }
                        } catch (IOException e) {
                            throw new RuntimeException("Error while synchronizing users with policy [" + policy.getName() + "].", e);
                        }
                    });
                }
            });
        }
    });
}
 
Example #27
Source File: AbstractShowTokensPage.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken getAccessToken() {
    try {
        return JsonSerialization.readValue(accessToken.getText(), AccessToken.class);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchElementException nsee) {
        log.warn("No accessToken element found on the page");
    }

    return null;
}
 
Example #28
Source File: AbstractShowTokensPage.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public RefreshToken getRefreshToken() {
    try {
        return JsonSerialization.readValue(refreshToken.getText(), RefreshToken.class);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchElementException nsee) {
        log.warn("No refreshToken element found on the page");
    }

    return null;
}
 
Example #29
Source File: UndeployedScriptMapperNotAvailableTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Deployment(name = SCRIPT_DEPLOYMENT_NAME, managed = false, testable = false)
@TargetsContainer(AUTH_SERVER_CURRENT)
public static JavaArchive deploy() throws IOException {
    ScriptProviderDescriptor representation = new ScriptProviderDescriptor();

    representation.addMapper("My Mapper", "mapper-a.js");

    return ShrinkWrap.create(JavaArchive.class, SCRIPT_DEPLOYMENT_NAME)
            .addAsManifestResource(new StringAsset(JsonSerialization.writeValueAsPrettyString(representation)),
                    "keycloak-scripts.json")
            .addAsResource("scripts/mapper-example.js", "mapper-a.js");
}
 
Example #30
Source File: KeycloakTestingClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public <T> T fetch(FetchOnServer function, Class<T> clazz) throws RunOnServerException {
    try {
        String s = fetchString(function);
        return s==null ? null : JsonSerialization.readValue(s, clazz);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}