Java Code Examples for org.keycloak.representations.idm.ClientRepresentation#setSecret()

The following examples show how to use org.keycloak.representations.idm.ClientRepresentation#setSecret() . 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: UserTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Test
public void countUsersNotServiceAccount() {
    createUsers();

    Integer count = realm.users().count();
    assertEquals(9, count.intValue());

    ClientRepresentation client = new ClientRepresentation();

    client.setClientId("test-client");
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setServiceAccountsEnabled(true);
    client.setEnabled(true);
    client.setRedirectUris(Arrays.asList("http://url"));

    getAdminClient().realm(REALM_NAME).clients().create(client);

    // KEYCLOAK-5660, should not consider service accounts
    assertEquals(9, realm.users().count().intValue());
}
 
Example 2
Source File: CustomAuthFlowCookieTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
@Override
public void beforeTest() {
    super.beforeTest();

    ClientRepresentation testApp = new ClientRepresentation();
    testApp.setClientId("test-app");
    testApp.setEnabled(true);
    testApp.setBaseUrl(APP_ROOT);
    testApp.setRedirectUris(Arrays.asList(new String[]{APP_ROOT + "/*"}));
    testApp.setAdminUrl(APP_ROOT + "/logout");
    testApp.setSecret("password");
    Response response = testRealmResource().clients().create(testApp);
    assertEquals(201, response.getStatus());
    getCleanup().addClientUuid(ApiUtil.getCreatedId(response));
    response.close();
}
 
Example 3
Source File: KcOidcBrokerConfiguration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public List<ClientRepresentation> createConsumerClients() {
    ClientRepresentation client = new ClientRepresentation();
    client.setId("broker-app");
    client.setClientId("broker-app");
    client.setName("broker-app");
    client.setSecret("broker-app-secret");
    client.setEnabled(true);
    client.setDirectAccessGrantsEnabled(true);

    client.setRedirectUris(Collections.singletonList(getConsumerRoot() +
            "/auth/*"));

    client.setBaseUrl(getConsumerRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/app");

    return Collections.singletonList(client);
}
 
Example 4
Source File: ConsentsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected List<ClientRepresentation> createProviderClients() {
    ClientRepresentation client = new ClientRepresentation();
    client.setId(CLIENT_ID);
    client.setName(CLIENT_ID);
    client.setSecret(CLIENT_SECRET);
    client.setEnabled(true);
    client.setConsentRequired(true);

    client.setRedirectUris(Collections.singletonList(getAuthRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_OIDC_ALIAS + "/endpoint/*"));

    client.setAdminUrl(getAuthRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_OIDC_ALIAS + "/endpoint");

    return Collections.singletonList(client);
}
 
Example 5
Source File: KeycloakTestResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static ClientRepresentation createClient(String clientId) {
    ClientRepresentation client = new ClientRepresentation();

    client.setClientId(clientId);
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setDirectAccessGrantsEnabled(true);
    client.setEnabled(true);

    client.setAuthorizationServicesEnabled(true);

    ResourceServerRepresentation authorizationSettings = new ResourceServerRepresentation();

    authorizationSettings.setResources(new ArrayList<>());
    authorizationSettings.setPolicies(new ArrayList<>());

    configurePermissionResourcePermission(authorizationSettings);
    configureClaimBasedPermission(authorizationSettings);
    configureHttpResponseClaimBasedPermission(authorizationSettings);
    configureBodyClaimBasedPermission(authorizationSettings);
    configurePaths(authorizationSettings);

    client.setAuthorizationSettings(authorizationSettings);

    return client;
}
 
Example 6
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
public void createClientWithServiceAccount() {
    ClientRepresentation client = new ClientRepresentation();
    client.setClientId(CLIENT_SERVICE_ACCOUNT);
    client.setName(CLIENT_SERVICE_ACCOUNT);
    client.setRootUrl("http://localhost/foo");
    client.setProtocol("openid-connect");
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setServiceAccountsEnabled(true);
    try (Response resp = testRealmResource().clients().create(client)) {
        String id = ApiUtil.getCreatedId(resp);
        UserRepresentation serviceAccountUser = testRealmResource().clients().get(id).getServiceAccountUser();
        assertNotNull(serviceAccountUser);
    }
}
 
Example 7
Source File: ClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void registerClientInMasterRealm() throws Exception {
    ClientRegistration masterReg = ClientRegistration.create().url(suiteContext.getAuthServerInfo().getContextRoot() + "/auth", "master").build();

    String token = oauth.doGrantAccessTokenRequest("master", "admin", "admin", null, Constants.ADMIN_CLI_CLIENT_ID, null).getAccessToken();
    masterReg.auth(Auth.token(token));

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId(CLIENT_ID);
    client.setSecret(CLIENT_SECRET);

    ClientRepresentation createdClient = masterReg.create(client);
    assertNotNull(createdClient);

    adminClient.realm("master").clients().get(createdClient.getId()).remove();
}
 
Example 8
Source File: ClientTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private ClientRepresentation createAppClient() {
    String redirectUri = oauth.getRedirectUri().replace("/master/", "/" + REALM_NAME + "/");

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("test-app");
    client.setAdminUrl(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/app/admin");
    client.setRedirectUris(Collections.singletonList(redirectUri));
    client.setSecret("secret");
    client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

    int notBefore = Time.currentTime() - 60;
    client.setNotBefore(notBefore);

    Response response = realm.clients().create(client);
    String id = ApiUtil.getCreatedId(response);
    getCleanup().addClientUuid(id);
    response.close();

    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), client, ResourceType.CLIENT);

    client.setId(id);
    return client;
}
 
Example 9
Source File: KeycloakTestResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static ClientRepresentation createClient(String clientId) {
    ClientRepresentation client = new ClientRepresentation();

    client.setClientId(clientId);
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setDirectAccessGrantsEnabled(true);
    client.setEnabled(true);

    client.setAuthorizationServicesEnabled(true);

    ResourceServerRepresentation authorizationSettings = new ResourceServerRepresentation();

    authorizationSettings.setResources(new ArrayList<>());
    authorizationSettings.setPolicies(new ArrayList<>());

    configurePermissionResourcePermission(authorizationSettings);
    configureClaimBasedPermission(authorizationSettings);
    configureHttpResponseClaimBasedPermission(authorizationSettings);
    configureBodyClaimBasedPermission(authorizationSettings);
    configurePaths(authorizationSettings);
    configureScopePermission(authorizationSettings);

    client.setAuthorizationSettings(authorizationSettings);

    return client;
}
 
Example 10
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRealmCreateClientWithMaster() throws Exception {
    ClientRepresentation rep = new ClientRepresentation();
    rep.setName("fullScopedClient");
    rep.setClientId("fullScopedClient");
    rep.setFullScopeAllowed(true);
    rep.setSecret("618268aa-51e6-4e64-93c4-3c0bc65b8171");
    rep.setProtocol("openid-connect");
    rep.setPublicClient(false);
    rep.setEnabled(true);
    adminClient.realm("master").clients().create(rep);

    RealmRepresentation newRealm=new RealmRepresentation();
    newRealm.setRealm("anotherRealm");
    newRealm.setId("anotherRealm");
    newRealm.setEnabled(true);
    adminClient.realms().create(newRealm);

    try {
        ClientRepresentation newClient = new ClientRepresentation();

        newClient.setName("newClient");
        newClient.setClientId("newClient");
        newClient.setFullScopeAllowed(true);
        newClient.setSecret("secret");
        newClient.setProtocol("openid-connect");
        newClient.setPublicClient(false);
        newClient.setEnabled(true);
        Response response = adminClient.realm("anotherRealm").clients().create(newClient);
        Assert.assertEquals(201, response.getStatus());
    } finally {
        adminClient.realm("anotherRealm").remove();

    }
}
 
Example 11
Source File: KcOidcBrokerClientSecretJwtTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<ClientRepresentation> createProviderClients() {
    List<ClientRepresentation> clientsRepList = super.createProviderClients();
    log.info("Update provider clients to accept JWT authentication");
    for (ClientRepresentation client: clientsRepList) {
        client.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
        client.setSecret(CLIENT_SECRET);
    }
    return clientsRepList;
}
 
Example 12
Source File: RealmTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setupTestAppAndUser() {
    testingClient.testApp().clearAdminActions();

    String redirectUri = oauth.getRedirectUri().replace("/master/", "/" + REALM_NAME + "/");

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("test-app");
    client.setAdminUrl(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/app/admin");
    client.setRedirectUris(Collections.singletonList(redirectUri));
    client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    client.setSecret("secret");
    Response resp = realm.clients().create(client);
    String clientDbId = ApiUtil.getCreatedId(resp);
    getCleanup().addClientUuid(clientDbId);
    resp.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(clientDbId), client, ResourceType.CLIENT);

    oauth.realm(REALM_NAME);
    oauth.redirectUri(redirectUri);

    UserRepresentation userRep = UserBuilder.create().username("testuser").build();
    Response response = realm.users().create(userRep);
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    getCleanup().addUserId(userId);
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId), userRep, ResourceType.USER);

    realm.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build());
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResetPasswordPath(userId), ResourceType.USER);

    testingClient.testApp().clearAdminActions();
}
 
Example 13
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation testRealmRep = loadTestRealm(testRealms);

    testRealmRep.setEventsEnabled(true);

    List<UserRepresentation> users = testRealmRep.getUsers();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("direct-login");
    user.setEmail("direct-login@localhost");
    user.setEnabled(true);
    List<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue("password");
    credentials.add(credential);
    user.setCredentials(credentials);
    users.add(user);

    List<ClientRepresentation> clients = testRealmRep.getClients();

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("resource-owner");
    client.setDirectAccessGrantsEnabled(true);
    client.setSecret("secret");
    clients.add(client);
}
 
Example 14
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation realmRepresentation = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
    RealmBuilder realm = RealmBuilder.edit(realmRepresentation).testEventListener();
    RealmRepresentation testRealm = realm.build();
    testRealms.add(testRealm);

    ClientRepresentation samlApp = KeycloakModelUtils.createClient(testRealm, "saml-client");
    samlApp.setSecret("secret");
    samlApp.setServiceAccountsEnabled(true);
    samlApp.setDirectAccessGrantsEnabled(true);
}
 
Example 15
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static ClientRepresentation createClient(String clientId) {
    ClientRepresentation client = new ClientRepresentation();

    client.setClientId(clientId);
    client.setEnabled(true);
    client.setRedirectUris(Arrays.asList("*"));
    client.setClientAuthenticatorType("client-secret");
    client.setSecret("secret");

    return client;
}
 
Example 16
Source File: ExportUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Full export of application including claims and secret
 * @param client
 * @return full ApplicationRepresentation
 */
public static ClientRepresentation exportClient(KeycloakSession session, ClientModel client) {
    ClientRepresentation clientRep = ModelToRepresentation.toRepresentation(client, session);
    clientRep.setSecret(client.getSecret());
    clientRep.setAuthorizationSettings(exportAuthorizationSettings(session,client));
    return clientRep;
}
 
Example 17
Source File: KeycloakModelUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static CredentialRepresentation generateSecret(ClientRepresentation client) {
    UserCredentialModel secret = UserCredentialModel.generateSecret();
    client.setSecret(secret.getChallengeResponse());
    return ModelToRepresentation.toRepresentation(secret);
}
 
Example 18
Source File: ClientRegistrationPoliciesTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientRepresentation createRep(String clientId) {
    ClientRepresentation client = new ClientRepresentation();
    client.setClientId(clientId);
    client.setSecret("test-secret");
    return client;
}
 
Example 19
Source File: StripSecretsUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static ClientRepresentation strip(ClientRepresentation rep) {
    if (rep.getSecret() != null) {
        rep.setSecret(maskNonVaultValue(rep.getSecret()));
    }
    return rep;
}
 
Example 20
Source File: AbstractClientRegistrationProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public ClientRepresentation create(ClientRegistrationContext context) {
    ClientRepresentation client = context.getClient();

    event.event(EventType.CLIENT_REGISTER);

    RegistrationAuth registrationAuth = auth.requireCreate(context);

    ValidationMessages validationMessages = new ValidationMessages();
    if (!context.validateClient(validationMessages)) {
        String errorCode = validationMessages.fieldHasError("redirectUris") ? ErrorCodes.INVALID_REDIRECT_URI : ErrorCodes.INVALID_CLIENT_METADATA;
        throw new ErrorResponseException(
                errorCode,
                validationMessages.getStringMessages(),
                Response.Status.BAD_REQUEST
        );
    }

    try {
        RealmModel realm = session.getContext().getRealm();
        ClientModel clientModel = new ClientManager(new RealmManager(session)).createClient(session, realm, client, true);

        if (clientModel.isServiceAccountsEnabled()) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
        }

        if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
            RepresentationToModel.createResourceServer(clientModel, session, true);
        }

        ClientRegistrationPolicyManager.triggerAfterRegister(context, registrationAuth, clientModel);

        client = ModelToRepresentation.toRepresentation(clientModel, session);

        client.setSecret(clientModel.getSecret());

        ClientValidationUtil.validate(session, clientModel, true, c -> {
            session.getTransactionManager().setRollbackOnly();
            throw  new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, c.getError(), Response.Status.BAD_REQUEST);
        });

        String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, clientModel, registrationAuth);
        client.setRegistrationAccessToken(registrationAccessToken);

        if (auth.isInitialAccessToken()) {
            ClientInitialAccessModel initialAccessModel = auth.getInitialAccessModel();
            session.realms().decreaseRemainingCount(realm, initialAccessModel);
        }

        event.client(client.getClientId()).success();
        return client;
    } catch (ModelDuplicateException e) {
        throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
    }
}