org.keycloak.admin.client.resource.ClientResource Java Examples

The following examples show how to use org.keycloak.admin.client.resource.ClientResource. 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: ClientAuthSecretSignedJWTTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCodeToTokenRequestFailureHS384Enforced() throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    final String realmName = "test";
    final String clientId = "test-app";
    try {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(realmName), clientId);
        clientRep = clientResource.toRepresentation();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setTokenEndpointAuthSigningAlg(Algorithm.HS384);
        clientResource.update(clientRep);

        testCodeToTokenRequestSuccess(Algorithm.HS384);
    } catch (Exception e) {
        Assert.fail();
    } finally {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(realmName), clientId);
        clientRep = clientResource.toRepresentation();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setTokenEndpointAuthSigningAlg(null);
        clientResource.update(clientRep);
    }
}
 
Example #2
Source File: MyResourcesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void afterAbstractKeycloakTestRealmImport() {
    ClientResource resourceServer = getResourceServer();
    AuthzClient authzClient = createAuthzClient(resourceServer.toRepresentation());
    AuthorizationResource authorization = resourceServer.authorization();
    ResourceRepresentation resource13 = null;
    for (int i = 1; i < 15; i++) {
        ResourceRepresentation resource = createResource(authzClient, authorization, i);
        if (i == 13) {
            resource13 = resource;
        }

        for (String scope : Arrays.asList("Scope A", "Scope B")) {
            createTicket(authzClient, i, resource, scope, userNames[i % userNames.length]);
        }
    }

    createTicket(authzClient, 13, resource13, "Scope A", "admin");
}
 
Example #3
Source File: RolePolicyManagementTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateClientRolePolicy() {
    ClientResource client = getClient();
    AuthorizationResource authorization = client.authorization();
    RolePolicyRepresentation representation = new RolePolicyRepresentation();

    representation.setName("Realm Client Role Policy");
    representation.setDescription("description");
    representation.setDecisionStrategy(DecisionStrategy.CONSENSUS);
    representation.setLogic(Logic.NEGATIVE);

    RolesResource roles = client.roles();

    roles.create(new RoleRepresentation("Client Role A", "desc", false));

    ClientRepresentation clientRep = client.toRepresentation();

    roles.create(new RoleRepresentation("Client Role B", "desc", false));

    representation.addRole("Client Role A");
    representation.addClientRole(clientRep.getClientId(), "Client Role B", true);

    assertCreated(authorization, representation);
}
 
Example #4
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void requestObjectRequiredAsRequestParamNotProvided() throws Exception {
    oauth.stateParamHardcoded("mystate2");
    // Set request object not required for client
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(OIDCConfigAttributes.REQUEST_OBJECT_REQUIRED_REQUEST);
    clientResource.update(clientRep);
    
    // Send request without request object
    // Assert that the request is not accepted
    oauth.openLoginForm();
    Assert.assertTrue(errorPage.isCurrent());
    assertEquals("Invalid Request", errorPage.getError());
    
    // Revert requiring request object for client
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(null);
    clientResource.update(clientRep);
}
 
Example #5
Source File: AuthorizationAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void configureAuthorization(String clientId) throws Exception {
    ClientResource client = getClient(getRealm(), clientId);
    AuthorizationResource authorization = client.authorization();
    ResourceRepresentation resource = new ResourceRepresentation("Resource A");

    Response response = authorization.resources().create(resource);
    response.close();

    JSPolicyRepresentation policy = new JSPolicyRepresentation();

    policy.setName("Default Policy");
    policy.setCode("$evaluation.grant();");

    response = authorization.policies().js().create(policy);
    response.close();

    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();

    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getName());
    permission.addPolicy(policy.getName());

    response = authorization.permissions().resource().create(permission);
    response.close();
}
 
Example #6
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void requestObjectNotRequiredProvidedInRequestUriParam() throws Exception {
    oauth.stateParamHardcoded("mystate2");
    // Set request object not required for client
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(null);
    clientResource.update(clientRep);
    
    // Set up a request object
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", oauth.getRedirectUri(), "10", Algorithm.none.toString());
    
    // Send request object reference in "request_uri" param
    oauth.requestUri(TestApplicationResourceUrls.clientRequestUri());
    // Assert that the request is accepted
    OAuthClient.AuthorizationEndpointResponse response2 = oauth.doLogin("test-user@localhost", "password");
    Assert.assertNotNull(response2.getCode());
    Assert.assertEquals("mystate2", response2.getState());
    assertTrue(appPage.isCurrent());
}
 
Example #7
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void requestObjectRequiredProvidedInRequestParam() throws Exception {
    oauth.stateParamHardcoded("mystate2");
    // Set request object not required for client
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(OIDCConfigAttributes.REQUEST_OBJECT_REQUIRED_REQUEST_OR_REQUEST_URI);
    clientResource.update(clientRep);
    
    // Set up a request object
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", oauth.getRedirectUri(), "10", Algorithm.none.toString());
    
    // Send request object in "request" param
    oauth.request(oidcClientEndpointsResource.getOIDCRequest());
    // Assert that the request is accepted
    OAuthClient.AuthorizationEndpointResponse response1 = oauth.doLogin("test-user@localhost", "password");
    Assert.assertNotNull(response1.getCode());
    Assert.assertEquals("mystate2", response1.getState());
    assertTrue(appPage.isCurrent());
    
    // Revert requiring request object for client
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(null);
    clientResource.update(clientRep);
}
 
Example #8
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void requestObjectRequiredProvidedInRequestUriParam() throws Exception {
    oauth.stateParamHardcoded("mystate2");
    // Set request object not required for client
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(OIDCConfigAttributes.REQUEST_OBJECT_REQUIRED_REQUEST_OR_REQUEST_URI);
    clientResource.update(clientRep);
    
    // Set up a request object
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", oauth.getRedirectUri(), "10", Algorithm.none.toString());
    
    // Send request object reference in "request_uri" param
    oauth.requestUri(TestApplicationResourceUrls.clientRequestUri());
    // Assert that the request is accepted
    OAuthClient.AuthorizationEndpointResponse response2 = oauth.doLogin("test-user@localhost", "password");
    Assert.assertNotNull(response2.getCode());
    Assert.assertEquals("mystate2", response2.getState());
    assertTrue(appPage.isCurrent());
    
    // Revert requiring request object for client
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(null);
    clientResource.update(clientRep);
}
 
Example #9
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void requestObjectRequiredAsRequestParamProvidedInRequestUriParam() throws Exception {
    oauth.stateParamHardcoded("mystate2");
    // Set request object not required for client
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(OIDCConfigAttributes.REQUEST_OBJECT_REQUIRED_REQUEST);
    clientResource.update(clientRep);
    
    // Set up a request object
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", oauth.getRedirectUri(), "10", Algorithm.none.toString());
    
    // Send request object reference in "request_uri" param
    oauth.requestUri(TestApplicationResourceUrls.clientRequestUri());
    // Assert that the request is accepted
    oauth.openLoginForm();
    Assert.assertTrue(errorPage.isCurrent());
    assertEquals("Invalid Request", errorPage.getError());
    
    // Revert requiring request object for client
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(null);
    clientResource.update(clientRep);
}
 
Example #10
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void requestObjectRequiredAsRequestUriParamProvidedInRequestParam() throws Exception {
    oauth.stateParamHardcoded("mystate2");
    // Set request object not required for client
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(OIDCConfigAttributes.REQUEST_OBJECT_REQUIRED_REQUEST_URI);
    clientResource.update(clientRep);
    
    // Set up a request object
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", oauth.getRedirectUri(), "10", Algorithm.none.toString());
    
    // Send request object in "request" param
    oauth.request(oidcClientEndpointsResource.getOIDCRequest());
    // Assert that the request is not accepted
    oauth.openLoginForm();
    Assert.assertTrue(errorPage.isCurrent());
    assertEquals("Invalid Request", errorPage.getError());
    
    // Revert requiring request object for client
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectRequired(null);
    clientResource.update(clientRep);
}
 
Example #11
Source File: AuthnRequestNameIdFormatTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedirectLoginNoNameIdPolicyForcePostBinding() throws Exception {
    ClientsResource clients = adminClient.realm(REALM_NAME).clients();
    List<ClientRepresentation> foundClients = clients.findByClientId(SAML_CLIENT_ID_SALES_POST);
    assertThat(foundClients, hasSize(1));
    ClientResource clientRes = clients.get(foundClients.get(0).getId());
    ClientRepresentation client = clientRes.toRepresentation();
    client.getAttributes().put(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "true");
    clientRes.update(client);

    testLoginWithNameIdPolicy(Binding.REDIRECT, Binding.POST, null, is("bburke"));

    // Revert
    client = clientRes.toRepresentation();
    client.getAttributes().put(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "false");
    clientRes.update(client);
}
 
Example #12
Source File: ClientTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void getClientSessions() throws Exception {
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
    assertEquals(200, response.getStatusCode());

    OAuthClient.AuthorizationEndpointResponse codeResponse = oauth.doLogin("test-user@localhost", "password");

    OAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(codeResponse.getCode(), "password");
    assertEquals(200, response2.getStatusCode());

    ClientResource app = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");

    assertEquals(2, (long) app.getApplicationSessionCount().get("count"));

    List<UserSessionRepresentation> userSessions = app.getUserSessions(0, 100);
    assertEquals(2, userSessions.size());
    assertEquals(1, userSessions.get(0).getClients().size());
}
 
Example #13
Source File: AbstractResourceServerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected ResourceRepresentation addResource(String resourceName, String owner, boolean ownerManagedAccess, String... scopeNames) throws Exception {
    ClientResource client = getClient(getRealm());
    AuthorizationResource authorization = client.authorization();
    ResourceRepresentation resource = new ResourceRepresentation(resourceName);

    if (owner != null) {
        resource.setOwner(new ResourceOwnerRepresentation(owner));
    }

    resource.setOwnerManagedAccess(ownerManagedAccess);
    resource.addScope(scopeNames);

    Response response = authorization.resources().create(resource);
    ResourceRepresentation temp = response.readEntity(ResourceRepresentation.class);
    resource.setId(temp.getId());
    response.close();

    return resource;
}
 
Example #14
Source File: OIDCPairwiseClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void updateToPairwiseThroughAdminRESTFailure() throws Exception {
    OIDCClientRepresentation response = create();
    Assert.assertEquals("public", response.getSubjectType());
    Assert.assertNull(response.getSectorIdentifierUri());

    // Push empty list to the sector identifier URI
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setSectorIdentifierRedirectUris(new ArrayList<>());

    String sectorIdentifierUri = TestApplicationResourceUrls.pairwiseSectorIdentifierUri();

    // Add protocolMapper through admin REST endpoint
    String clientId = response.getClientId();
    ProtocolMapperRepresentation pairwiseProtMapper = SHA256PairwiseSubMapper.createPairwiseMapper(sectorIdentifierUri, null);
    RealmResource realmResource = realmsResouce().realm("test");
    ClientResource clientResource = ApiUtil.findClientByClientId(realmsResouce().realm("test"), clientId);
    Response resp = clientResource.getProtocolMappers().createMapper(pairwiseProtMapper);
    Assert.assertEquals(400, resp.getStatus());

    // Assert still public
    reg.auth(Auth.token(response));
    OIDCClientRepresentation rep = reg.oidc().get(response.getClientId());
    Assert.assertEquals("public", rep.getSubjectType());
    Assert.assertNull(rep.getSectorIdentifierUri());
}
 
Example #15
Source File: SessionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUserSessions() {
    //List<java.util.Map<String, String>> stats = this.testRealmResource().getClientSessionStats();
    ClientResource account = findClientResourceById("account");

    testRealmAccountManagementPage.navigateTo();
    loginPage.form().login(testUser);

    List<UserSessionRepresentation> sessions = account.getUserSessions(0, 5);
    assertEquals(1, sessions.size());

    UserSessionRepresentation rep = sessions.get(0);

    UserRepresentation testUserRep = getFullUserRep(testUser.getUsername());
    assertEquals(testUserRep.getId(), rep.getUserId());
    assertEquals(testUserRep.getUsername(), rep.getUsername());

    String clientId = account.toRepresentation().getId();
    assertEquals("account", rep.getClients().get(clientId));
    assertNotNull(rep.getIpAddress());
    assertNotNull(rep.getLastAccess());
    assertNotNull(rep.getStart());

    testRealmAccountManagementPage.signOut();
}
 
Example #16
Source File: ClientAuthSignedJWTTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCodeToTokenRequestSuccessES256Enforced() throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "client2");
        clientRep = clientResource.toRepresentation();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setTokenEndpointAuthSigningAlg(Algorithm.ES256);
        clientResource.update(clientRep);

        testCodeToTokenRequestSuccess(Algorithm.ES256);
    } catch (Exception e) {
        Assert.fail();
    } finally {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "client2");
        clientRep = clientResource.toRepresentation();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setTokenEndpointAuthSigningAlg(null);
        clientResource.update(clientRep);
    }
}
 
Example #17
Source File: ConflictingScopePermissionTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Scope Read on Resource A has two conflicting permissions. One is granting access for Marta and the other for Kolo.
 *
 * <p>Scope Read should not be granted for Marta.
 */
@Test
public void testMartaCanAccessResourceA() throws Exception {
    ClientResource client = getClient(getRealm());
    AuthorizationResource authorization = client.authorization();
    ResourceServerRepresentation settings = authorization.getSettings();

    settings.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
    settings.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    authorization.update(settings);

    Collection<Permission> permissions = getEntitlements("marta", "password");

    assertEquals(1, permissions.size());

    for (Permission permission : new ArrayList<>(permissions)) {
        String resourceSetName = permission.getResourceName();

        switch (resourceSetName) {
            case "Resource A":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write", "read"));
                permissions.remove(permission);
                break;
            case "Resource C":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write", "read"));
                permissions.remove(permission);
                break;
            default:
                fail("Unexpected permission for resource [" + resourceSetName + "]");
        }
    }

    assertTrue(permissions.isEmpty());
}
 
Example #18
Source File: ConflictingScopePermissionTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Scope Read on Resource A has two conflicting permissions. One is granting access for Marta and the other for Kolo.
 *
 * <p>Scope Read should not be granted for Marta.
 */
@Test
public void testMartaCanAccessResourceAWithExecuteAndWrite() throws Exception {
    ClientResource client = getClient(getRealm());
    AuthorizationResource authorization = client.authorization();
    ResourceServerRepresentation settings = authorization.getSettings();

    settings.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
    settings.setDecisionStrategy(DecisionStrategy.UNANIMOUS);

    authorization.update(settings);

    Collection<Permission> permissions = getEntitlements("marta", "password");

    assertEquals(1, permissions.size());

    for (Permission permission : new ArrayList<>(permissions)) {
        String resourceSetName = permission.getResourceName();

        switch (resourceSetName) {
            case "Resource A":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write"));
                permissions.remove(permission);
                break;
            case "Resource C":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write", "read"));
                permissions.remove(permission);
                break;
            default:
                fail("Unexpected permission for resource [" + resourceSetName + "]");
        }
    }

    assertTrue(permissions.isEmpty());
}
 
Example #19
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ResourceRepresentation createResource(ClientResource clientResource, String name, String uri, String... scopes) {
    ResourceRepresentation representation = new ResourceRepresentation();

    representation.setName(name);
    representation.setUri(uri);
    representation.setScopes(Arrays.asList(scopes).stream().map(ScopeRepresentation::new).collect(Collectors.toSet()));

    try (javax.ws.rs.core.Response response = clientResource.authorization().resources().create(representation)) {

        representation.setId(response.readEntity(ResourceRepresentation.class).getId());

        return representation;
    }
}
 
Example #20
Source File: ClientRepository.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
public void removeProtocolMappers(String realm, String clientId, List<ProtocolMapperRepresentation> protocolMappers) {
    ClientResource clientResource = loadClientById(realm, clientId);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();

    List<ProtocolMapperRepresentation> existingProtocolMappers = clientResource.getProtocolMappers().getMappers();
    List<ProtocolMapperRepresentation> protocolMapperToRemove = existingProtocolMappers.stream().filter(em -> protocolMappers.stream().anyMatch(m -> Objects.equals(m.getName(), em.getName()))).collect(Collectors.toList());

    for (ProtocolMapperRepresentation protocolMapper : protocolMapperToRemove) {
        protocolMappersResource.delete(protocolMapper.getId());
    }
}
 
Example #21
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test
public void testAddClientsWithServiceAccountsAndAuthorization() throws IOException {
    setFail();
    addClients(true);

    PartialImportResults results = doImport();
    assertEquals(NUM_ENTITIES * 2, results.getAdded());

    for (PartialImportResult result : results.getResults()) {
        if (result.getResourceType().equals(ResourceType.CLIENT)) {
            String id = result.getId();
            ClientResource clientRsc = testRealmResource().clients().get(id);
            ClientRepresentation client = clientRsc.toRepresentation();
            assertTrue(client.getName().startsWith(CLIENT_PREFIX));
            Assert.assertTrue(client.isServiceAccountsEnabled());
            Assert.assertTrue(client.getAuthorizationServicesEnabled());
            AuthorizationResource authRsc = clientRsc.authorization();
            ResourceServerRepresentation authRep = authRsc.exportSettings();
            Assert.assertNotNull(authRep);
            Assert.assertEquals(2, authRep.getResources().size());
            Assert.assertEquals(3, authRep.getPolicies().size());
        } else {
            UserResource userRsc = testRealmResource().users().get(result.getId());
            Assert.assertTrue(userRsc.toRepresentation().getUsername().startsWith(
                    ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + CLIENT_PREFIX));
        }
    }
}
 
Example #22
Source File: ResourcesRestServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void after() {
    super.after();
    ClientResource resourceServer = getResourceServer();
    ClientRepresentation representation = resourceServer.toRepresentation();
    representation.setAuthorizationServicesEnabled(false);
    resourceServer.update(representation);
    representation.setAuthorizationServicesEnabled(true);
    resourceServer.update(representation);
}
 
Example #23
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientDisplayedOnConsentScreenWithEmptyConsentText() throws Exception {
    // Add "displayOnConsentScreen" to client
    ClientResource thirdParty = ApiUtil.findClientByClientId(testRealm(), "third-party");
    ClientRepresentation thirdPartyRep = thirdParty.toRepresentation();
    thirdPartyRep.getAttributes().put(ClientScopeModel.DISPLAY_ON_CONSENT_SCREEN, "true");
    thirdPartyRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, "");
    thirdParty.update(thirdPartyRep);

    // Change consent text on profile scope
    ClientScopeResource profileScope = ApiUtil.findClientScopeByName(testRealm(), OAuth2Constants.SCOPE_PROFILE);
    ClientScopeRepresentation profileScopeRep = profileScope.toRepresentation();
    profileScopeRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, " ");
    profileScope.update(profileScopeRep);

    // Login. ConsentTexts are empty for the client and for the "profile" scope, so it should fallback to name/clientId
    oauth.clientId("third-party");
    oauth.doLoginGrant("john", "password");

    grantPage.assertCurrent();
    grantPage.assertGrants("profile", OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT, "third-party");
    grantPage.accept();

    // Revert
    profileScopeRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, OIDCLoginProtocolFactory.PROFILE_SCOPE_CONSENT_TEXT);
    profileScope.update(profileScopeRep);

    thirdPartyRep.getAttributes().put(ClientScopeModel.DISPLAY_ON_CONSENT_SCREEN, "false");
    thirdParty.update(thirdPartyRep);
}
 
Example #24
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientDisplayedOnConsentScreen() throws Exception {
    // Add "displayOnConsentScreen" to client
    ClientResource thirdParty = ApiUtil.findClientByClientId(testRealm(), "third-party");
    ClientRepresentation thirdPartyRep = thirdParty.toRepresentation();
    thirdPartyRep.getAttributes().put(ClientScopeModel.DISPLAY_ON_CONSENT_SCREEN, "true");
    thirdPartyRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, "ThirdParty permissions");
    thirdParty.update(thirdPartyRep);

    // Login. Client should be displayed on consent screen
    oauth.clientId("third-party");
    oauth.doLoginGrant("john", "password");

    grantPage.assertCurrent();
    grantPage.assertGrants(OAuthGrantPage.PROFILE_CONSENT_TEXT, OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT, "ThirdParty permissions");
    grantPage.accept();

    EventRepresentation loginEvent = events.expectLogin()
            .user(userId)
            .client("third-party")
            .detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED)
            .assertEvent();

    Tokens tokens = sendTokenRequest(loginEvent, userId,"openid email profile", "third-party");
    IDToken idToken = tokens.idToken;

    assertProfile(idToken, true);
    assertEmail(idToken, true);
    assertAddress(idToken, false);
    assertPhone(idToken, false);

    // Revert
    thirdPartyRep.getAttributes().put(ClientScopeModel.DISPLAY_ON_CONSENT_SCREEN, "false");
    thirdParty.update(thirdPartyRep);
}
 
Example #25
Source File: CustomImportService.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
private void removeImpersonationRoleFromClient(RealmResource master, String clientId) {
    ClientRepresentation client = clientRepository.getClientByClientId("master", clientId);
    ClientResource clientResource = master.clients()
            .get(client.getId());

    RoleResource impersonationRole = clientResource.roles().get("impersonation");

    try {
        logger.debug("Remove role 'impersonation' from client '{}' in realm 'master'", clientId);

        impersonationRole.remove();
    } catch (javax.ws.rs.NotFoundException e) {
        logger.info("Cannot remove 'impersonation' role from client '{}' in 'master' realm: Not found", clientId);
    }
}
 
Example #26
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testRolesAndAllowedOriginsRemovedFromAccessToken() throws Exception {
    RealmResource realm = adminClient.realm("test");
    ClientScopeRepresentation allowedOriginsScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE).toRepresentation();
    ClientScopeRepresentation rolesScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE).toRepresentation();

    // Remove 'roles' and 'web-origins' scope from the client
    ClientResource testApp = ApiUtil.findClientByClientId(realm, "test-app");
    testApp.removeDefaultClientScope(allowedOriginsScope.getId());
    testApp.removeDefaultClientScope(rolesScope.getId());

    try {
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");
        AccessToken accessToken = oauth.verifyToken(response.getAccessToken());

        // Assert web origins are not in the token
        Assert.assertNull(accessToken.getAllowedOrigins());

        // Assert roles are not in the token
        Assert.assertNull(accessToken.getRealmAccess());
        Assert.assertTrue(accessToken.getResourceAccess().isEmpty());

        // Assert client not in the token audience. Just in "issuedFor"
        Assert.assertEquals("test-app", accessToken.getIssuedFor());
        Assert.assertFalse(accessToken.hasAudience("test-app"));

        // Assert IDToken still has "test-app" as an audience
        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        Assert.assertEquals("test-app", idToken.getIssuedFor());
        Assert.assertTrue(idToken.hasAudience("test-app"));
    } finally {
        // Revert
        testApp.addDefaultClientScope(allowedOriginsScope.getId());
        testApp.addDefaultClientScope(rolesScope.getId());
    }
}
 
Example #27
Source File: OfflineTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * KEYCLOAK-4201
 *
 * @throws Exception
 */
@Test
public void offlineTokenAdminRESTAccess() throws Exception {
    // Grant "view-realm" role to user
    RealmResource appRealm = adminClient.realm("test");
    ClientResource realmMgmt = ApiUtil.findClientByClientId(appRealm, Constants.REALM_MANAGEMENT_CLIENT_ID);
    String realmMgmtUuid = realmMgmt.toRepresentation().getId();
    RoleRepresentation roleRep = realmMgmt.roles().get(AdminRoles.VIEW_REALM).toRepresentation();

    UserResource testUser = findUserByUsernameId(appRealm, "test-user@localhost");
    testUser.roles().clientLevel(realmMgmtUuid).add(Collections.singletonList(roleRep));

    // Login with offline token now
    oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
    oauth.clientId("offline-client");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("secret1", "test-user@localhost", "password");

    events.clear();

    // Set the time offset, so that "normal" userSession expires
    setTimeOffset(86400);

    // Remove expired sessions. This will remove "normal" userSession
    testingClient.testing().removeUserSessions(appRealm.toRepresentation().getId());

    // Refresh with the offline token
    tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "secret1");

    // Use accessToken to admin REST request
    try (Keycloak offlineTokenAdmin = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
            AuthRealm.MASTER, Constants.ADMIN_CLI_CLIENT_ID, tokenResponse.getAccessToken(), TLSUtils.initializeTLS())) {
        RealmRepresentation testRealm = offlineTokenAdmin.realm("test").toRepresentation();
        Assert.assertNotNull(testRealm);
    }
}
 
Example #28
Source File: ApiUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientResource findClientResourceById(RealmResource realm, String id) {
    for (ClientRepresentation c : realm.clients().findAll()) {
        if (c.getId().equals(id)) {
            return realm.clients().get(c.getId());
        }
    }
    return null;
}
 
Example #29
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyTokenAudience() throws Exception {
    // Generate audience client scope
    String clientScopeId = testingClient.testing().generateAudienceClientScope("demo", "customer-db-audience-required");

    ClientResource client = ApiUtil.findClientByClientId(adminClient.realm("demo"), "customer-portal");
    client.addOptionalClientScope(clientScopeId);

    // Login without audience scope. Invoke service should end with failure
    driver.navigate().to(customerPortal.callCustomerDbAudienceRequiredUrl(false).toURL());
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(customerPortal.callCustomerDbAudienceRequiredUrl(false));

    String pageSource = driver.getPageSource();
    Assert.assertTrue(pageSource.contains("Service returned: 401"));
    Assert.assertFalse(pageSource.contains("Stian Thorgersen"));

    // Logout TODO: will be good to not request logout to force adapter to use additional scope (and other request parameters)
    driver.navigate().to(customerPortal.logout().toURL());
    waitForPageToLoad();

    // Login with requested audience
    driver.navigate().to(customerPortal.callCustomerDbAudienceRequiredUrl(true).toURL());
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(customerPortal.callCustomerDbAudienceRequiredUrl(false));

    pageSource = driver.getPageSource();
    Assert.assertFalse(pageSource.contains("Service returned: 401"));
    assertLogged();

    // logout
    String logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder())
            .queryParam(OAuth2Constants.REDIRECT_URI, customerPortal.toString()).build("demo").toString();
    driver.navigate().to(logoutUri);
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
}
 
Example #30
Source File: FixedHostnameTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertSamlLogin(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws Exception {
    final String realmUrl = expectedBaseUrl + "/auth/realms/" + realm;
    final String baseSamlEndpointUrl = realmUrl + "/protocol/saml";
    String entityDescriptor = null;
    RealmResource realmResource = testAdminClient.realm(realm);
    ClientRepresentation clientRep = ClientBuilder.create()
      .protocol(SamlProtocol.LOGIN_PROTOCOL)
      .clientId(SAML_CLIENT_ID)
      .enabled(true)
      .attribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
      .redirectUris("http://foo.bar/")
      .build();
    try (Creator<ClientResource> c = Creator.create(realmResource, clientRep);
      Creator<UserResource> u = Creator.create(realmResource, UserBuilder.create().username("bicycle").password("race").enabled(true).build())) {
        SAMLDocumentHolder samlResponse = new SamlClientBuilder()
          .authnRequest(new URI(baseSamlEndpointUrl), SAML_CLIENT_ID, "http://foo.bar/", Binding.POST).build()
          .login().user("bicycle", "race").build()
          .getSamlResponse(Binding.POST);

        assertThat(samlResponse.getSamlObject(), org.keycloak.testsuite.util.Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
        ResponseType response = (ResponseType) samlResponse.getSamlObject();

        assertThat(response.getAssertions(), hasSize(1));
        assertThat(response.getAssertions().get(0).getAssertion().getIssuer().getValue(), is(realmUrl));
    } catch (Exception e) {
        log.errorf("Caught exception while parsing SAML descriptor %s", entityDescriptor);
    }
}