Java Code Examples for org.keycloak.representations.idm.RealmRepresentation#getRealm()

The following examples show how to use org.keycloak.representations.idm.RealmRepresentation#getRealm() . 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: TestsHelper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static boolean importTestRealm(String username, String password, String realmJsonPath) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        ClassLoader classLoader = TestsHelper.class.getClassLoader();
        InputStream stream = TestsHelper.class.getResourceAsStream(realmJsonPath);
        RealmRepresentation realmRepresentation = mapper.readValue(stream, RealmRepresentation.class);

        Keycloak keycloak = Keycloak.getInstance(
                keycloakBaseUrl,
                "master",
                username,
                password,
                "admin-cli");
        keycloak.realms().create(realmRepresentation);
        testRealm = realmRepresentation.getRealm();
        generateInitialAccessToken(keycloak);
        return true;

    }
 
Example 2
Source File: RealmRepository.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
public void create(RealmRepresentation realmToCreate) {
    Keycloak keycloak = keycloakProvider.get();
    RealmsResource realmsResource = keycloak.realms();

    try {
        realmsResource.create(realmToCreate);
    } catch (WebApplicationException error) {
        String errorMessage = ResponseUtil.getErrorMessage(error);
        throw new KeycloakRepositoryException(
                "Cannot create realm '" + realmToCreate.getRealm() + "': " + errorMessage,
                error
        );
    }
}
 
Example 3
Source File: RealmInvalidationClusterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected RealmRepresentation testEntityUpdates(RealmRepresentation realm, boolean backendFailover) {

    // realm name
    String originalName = realm.getRealm();
    realm.setRealm(realm.getRealm() + "_updated");
    realm = updateEntity(originalName, realm, getCurrentFailNode());
    verifyEntityUpdateDuringFailover(realm, backendFailover);

    // enabled
    realm.setEnabled(!realm.isEnabled());
    realm = updateEntityOnCurrentFailNode(realm, "enabled");
    verifyEntityUpdateDuringFailover(realm, backendFailover);

    // public key
    realm.setPublicKey("GENERATE");
    realm = updateEntityOnCurrentFailNode(realm, "public key");
    assertNotEquals("GENERATE", realm.getPublicKey());
    verifyEntityUpdateDuringFailover(realm, backendFailover);

    // require ssl
    realm.setSslRequired("all");
    realm = updateEntityOnCurrentFailNode(realm, "require ssl");
    verifyEntityUpdateDuringFailover(realm, backendFailover);

    // brute force detection
    realm.setBruteForceProtected(!realm.isBruteForceProtected());
    realm = updateEntityOnCurrentFailNode(realm, "brute force");
    verifyEntityUpdateDuringFailover(realm, backendFailover);

    // brute force detection - failure factor
    realm.setBruteForceProtected(true);
    realm.setFailureFactor(realm.getFailureFactor() + 1);
    realm = updateEntityOnCurrentFailNode(realm, "brute force failure factor");
    verifyEntityUpdateDuringFailover(realm, backendFailover);

    return realm;
}
 
Example 4
Source File: AbstractAdminCrossDCTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    log.debug("Configuring test realm '" + testRealm.getRealm() + "'. Enabling direct access grant.");
    ClientRepresentation testApp = findTestApp(testRealm);
    if (testApp == null) {
        throw new IllegalStateException("Couldn't find the 'test-app' within the realm '" + testRealm.getRealm() + "'");
    }
    testApp.setDirectAccessGrantsEnabled(true);
}
 
Example 5
Source File: FluentTestsHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Import a test realm.
 *
 * @param stream A stream representing a JSON file with an exported realm.
 * @return <code>this</code>
 * @throws IOException Thrown in case of parsing error.
 */
public FluentTestsHelper importTestRealm(InputStream stream) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    RealmRepresentation realmRepresentation = mapper.readValue(stream, RealmRepresentation.class);
    keycloak.realms().create(realmRepresentation);
    testRealm = realmRepresentation.getRealm();
    accessToken = generateInitialAccessToken();
    return this;
}
 
Example 6
Source File: ImportUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Fully import realm from representation, save it to model and return model of newly created realm
 *
 * @param session
 * @param rep
 * @param strategy specifies whether to overwrite or ignore existing realm or user entries
 * @param skipUserDependent If true, then import of any models, which needs users already imported in DB, will be skipped. For example authorization
 * @return newly imported realm (or existing realm if ignoreExisting is true and realm of this name already exists)
 */
public static boolean importRealm(KeycloakSession session, RealmRepresentation rep, Strategy strategy, boolean skipUserDependent) {
    String realmName = rep.getRealm();
    RealmProvider model = session.realms();
    RealmModel realm = model.getRealmByName(realmName);

    if (realm != null) {
        if (strategy == Strategy.IGNORE_EXISTING) {
            logger.infof("Realm '%s' already exists. Import skipped", realmName);
            return false;
        } else {
            logger.infof("Realm '%s' already exists. Removing it before import", realmName);
            if (Config.getAdminRealm().equals(realm.getId())) {
                // Delete all masterAdmin apps due to foreign key constraints
                for (RealmModel currRealm : model.getRealms()) {
                    currRealm.setMasterAdminClient(null);
                }
            }
            // TODO: For migration between versions, it should be possible to delete just realm but keep it's users
            model.removeRealm(realm.getId());
        }
    }

    RealmManager realmManager = new RealmManager(session);
    realmManager.importRealm(rep, skipUserDependent);

    if (System.getProperty(ExportImportConfig.ACTION) != null) {
        logger.infof("Realm '%s' imported", realmName);
    }
    
    return true;
}
 
Example 7
Source File: Creator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static Creator<RealmResource> create(Keycloak adminClient, RealmRepresentation rep) {
    adminClient.realms().create(rep);
    final RealmResource r = adminClient.realm(rep.getRealm());
    LOG.debugf("Created realm %s", rep.getRealm());
    return new Creator(rep.getRealm(), r, r::remove);
}
 
Example 8
Source File: RealmTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void assertRealm(RealmRepresentation realm, RealmRepresentation storedRealm) {
    if (realm.getId() != null) {
        assertEquals(realm.getId(), storedRealm.getId());
    }
    if (realm.getRealm() != null) {
        assertEquals(realm.getRealm(), storedRealm.getRealm());
    }
    if (realm.isEnabled() != null) assertEquals(realm.isEnabled(), storedRealm.isEnabled());
    if (realm.isBruteForceProtected() != null) assertEquals(realm.isBruteForceProtected(), storedRealm.isBruteForceProtected());
    if (realm.getMaxFailureWaitSeconds() != null) assertEquals(realm.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds());
    if (realm.getMinimumQuickLoginWaitSeconds() != null) assertEquals(realm.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds());
    if (realm.getWaitIncrementSeconds() != null) assertEquals(realm.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds());
    if (realm.getQuickLoginCheckMilliSeconds() != null) assertEquals(realm.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds());
    if (realm.getMaxDeltaTimeSeconds() != null) assertEquals(realm.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds());
    if (realm.getFailureFactor() != null) assertEquals(realm.getFailureFactor(), storedRealm.getFailureFactor());
    if (realm.isRegistrationAllowed() != null) assertEquals(realm.isRegistrationAllowed(), storedRealm.isRegistrationAllowed());
    if (realm.isRegistrationEmailAsUsername() != null) assertEquals(realm.isRegistrationEmailAsUsername(), storedRealm.isRegistrationEmailAsUsername());
    if (realm.isRememberMe() != null) assertEquals(realm.isRememberMe(), storedRealm.isRememberMe());
    if (realm.isVerifyEmail() != null) assertEquals(realm.isVerifyEmail(), storedRealm.isVerifyEmail());
    if (realm.isLoginWithEmailAllowed() != null) assertEquals(realm.isLoginWithEmailAllowed(), storedRealm.isLoginWithEmailAllowed());
    if (realm.isDuplicateEmailsAllowed() != null) assertEquals(realm.isDuplicateEmailsAllowed(), storedRealm.isDuplicateEmailsAllowed());
    if (realm.isResetPasswordAllowed() != null) assertEquals(realm.isResetPasswordAllowed(), storedRealm.isResetPasswordAllowed());
    if (realm.isEditUsernameAllowed() != null) assertEquals(realm.isEditUsernameAllowed(), storedRealm.isEditUsernameAllowed());
    if (realm.getSslRequired() != null) assertEquals(realm.getSslRequired(), storedRealm.getSslRequired());
    if (realm.getAccessCodeLifespan() != null) assertEquals(realm.getAccessCodeLifespan(), storedRealm.getAccessCodeLifespan());
    if (realm.getAccessCodeLifespanUserAction() != null)
        assertEquals(realm.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction());
    if (realm.getActionTokenGeneratedByAdminLifespan() != null)
        assertEquals(realm.getActionTokenGeneratedByAdminLifespan(), storedRealm.getActionTokenGeneratedByAdminLifespan());
    if (realm.getActionTokenGeneratedByUserLifespan() != null)
        assertEquals(realm.getActionTokenGeneratedByUserLifespan(), storedRealm.getActionTokenGeneratedByUserLifespan());
    else
        assertEquals(realm.getAccessCodeLifespanUserAction(), storedRealm.getActionTokenGeneratedByUserLifespan());
    if (realm.getNotBefore() != null) assertEquals(realm.getNotBefore(), storedRealm.getNotBefore());
    if (realm.getAccessTokenLifespan() != null) assertEquals(realm.getAccessTokenLifespan(), storedRealm.getAccessTokenLifespan());
    if (realm.getAccessTokenLifespanForImplicitFlow() != null) assertEquals(realm.getAccessTokenLifespanForImplicitFlow(), storedRealm.getAccessTokenLifespanForImplicitFlow());
    if (realm.getSsoSessionIdleTimeout() != null) assertEquals(realm.getSsoSessionIdleTimeout(), storedRealm.getSsoSessionIdleTimeout());
    if (realm.getSsoSessionMaxLifespan() != null) assertEquals(realm.getSsoSessionMaxLifespan(), storedRealm.getSsoSessionMaxLifespan());
    if (realm.getSsoSessionIdleTimeoutRememberMe() != null) Assert.assertEquals(realm.getSsoSessionIdleTimeoutRememberMe(), storedRealm.getSsoSessionIdleTimeoutRememberMe());
    if (realm.getSsoSessionMaxLifespanRememberMe() != null) Assert.assertEquals(realm.getSsoSessionMaxLifespanRememberMe(), storedRealm.getSsoSessionMaxLifespanRememberMe());
    if (realm.getClientSessionIdleTimeout() != null)
        Assert.assertEquals(realm.getClientSessionIdleTimeout(), storedRealm.getClientSessionIdleTimeout());
    if (realm.getClientSessionMaxLifespan() != null)
        Assert.assertEquals(realm.getClientSessionMaxLifespan(), storedRealm.getClientSessionMaxLifespan());
    if (realm.getClientOfflineSessionIdleTimeout() != null)
        Assert.assertEquals(realm.getClientOfflineSessionIdleTimeout(), storedRealm.getClientOfflineSessionIdleTimeout());
    if (realm.getClientOfflineSessionMaxLifespan() != null)
        Assert.assertEquals(realm.getClientOfflineSessionMaxLifespan(), storedRealm.getClientOfflineSessionMaxLifespan());
    if (realm.getRequiredCredentials() != null) {
        assertNotNull(storedRealm.getRequiredCredentials());
        for (String cred : realm.getRequiredCredentials()) {
            assertTrue(storedRealm.getRequiredCredentials().contains(cred));
        }
    }
    if (realm.getLoginTheme() != null) assertEquals(realm.getLoginTheme(), storedRealm.getLoginTheme());
    if (realm.getAccountTheme() != null) assertEquals(realm.getAccountTheme(), storedRealm.getAccountTheme());
    if (realm.getAdminTheme() != null) assertEquals(realm.getAdminTheme(), storedRealm.getAdminTheme());
    if (realm.getEmailTheme() != null) assertEquals(realm.getEmailTheme(), storedRealm.getEmailTheme());

    if (realm.getPasswordPolicy() != null) assertEquals(realm.getPasswordPolicy(), storedRealm.getPasswordPolicy());

    if (realm.getDefaultRoles() != null) {
        assertNotNull(storedRealm.getDefaultRoles());
        for (String role : realm.getDefaultRoles()) {
            assertTrue(storedRealm.getDefaultRoles().contains(role));
        }
    }

    if (realm.getSmtpServer() != null) {
        assertEquals(realm.getSmtpServer(), storedRealm.getSmtpServer());
    }

    if (realm.getBrowserSecurityHeaders() != null) {
        assertEquals(realm.getBrowserSecurityHeaders(), storedRealm.getBrowserSecurityHeaders());
    }

    if (realm.getAttributes() != null) {
        HashMap<String, String> attributes = new HashMap<>();
        attributes.putAll(storedRealm.getAttributes());
        attributes.entrySet().retainAll(realm.getAttributes().entrySet());
        assertEquals(realm.getAttributes(), attributes);
    }

    if (realm.isUserManagedAccessAllowed() != null) assertEquals(realm.isUserManagedAccessAllowed(), storedRealm.isUserManagedAccessAllowed());
}
 
Example 9
Source File: AbstractInvalidationClusterTestWithTestRealm.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void createTestRealm(ContainerInfo node) {
    RealmRepresentation r = createTestRealmRepresentation();
    getAdminClientFor(node).realms().create(r);
    testRealmName = r.getRealm();
}
 
Example 10
Source File: RequiredActionsTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void testBarcodeOtp() throws Exception {
    assumeFalse(driver instanceof HtmlUnitDriver); // HtmlUnit browser cannot take screenshots
    TakesScreenshot screenshotDriver = (TakesScreenshot) driver;
    QRCodeReader qrCodeReader = new QRCodeReader();

    initiateRequiredAction(otpSetupPage);

    otpSetupPage.localeDropdown().selectAndAssert(CUSTOM_LOCALE_NAME);

    otpSetupPage.clickManualMode();
    otpSetupPage.clickBarcodeMode();

    assertTrue(otpSetupPage.isBarcodePresent());
    assertFalse(otpSetupPage.isSecretKeyPresent());
    assertTrue(otpSetupPage.feedbackMessage().isWarning());
    assertEquals("You need to set up Mobile Authenticator to activate your account.", otpSetupPage.feedbackMessage().getText());

    // empty input
    otpSetupPage.submit();
    assertTrue(otpSetupPage.feedbackMessage().isError());
    assertEquals("Please specify authenticator code.", otpSetupPage.feedbackMessage().getText());

    // take a screenshot of the QR code
    byte[] screenshot = screenshotDriver.getScreenshotAs(OutputType.BYTES);
    BufferedImage screenshotImg = ImageIO.read(new ByteArrayInputStream(screenshot));
    BinaryBitmap screenshotBinaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(screenshotImg)));
    Result qrCode = qrCodeReader.decode(screenshotBinaryBitmap);

    // parse the QR code string
    Pattern qrUriPattern = Pattern.compile("^otpauth:\\/\\/(?<type>.+)\\/(?<realm>.+):(?<user>.+)\\?secret=(?<secret>.+)&digits=(?<digits>.+)&algorithm=(?<algorithm>.+)&issuer=(?<issuer>.+)&(?:period=(?<period>.+)|counter=(?<counter>.+))$");
    Matcher qrUriMatcher = qrUriPattern.matcher(qrCode.getText());
    assertTrue(qrUriMatcher.find());

    // extract data
    String type = qrUriMatcher.group("type");
    String realm = qrUriMatcher.group("realm");
    String user = qrUriMatcher.group("user");
    String secret = qrUriMatcher.group("secret");
    int digits = Integer.parseInt(qrUriMatcher.group("digits"));
    String algorithm = qrUriMatcher.group("algorithm");
    String issuer = qrUriMatcher.group("issuer");
    Integer period = type.equals(TOTP) ? Integer.parseInt(qrUriMatcher.group("period")) : null;
    Integer counter = type.equals(HOTP) ? Integer.parseInt(qrUriMatcher.group("counter")) : null;

    RealmRepresentation realmRep = testRealmResource().toRepresentation();
    String expectedRealmName = realmRep.getDisplayName() != null && !realmRep.getDisplayName().isEmpty() ? realmRep.getDisplayName() : realmRep.getRealm();

    // basic assertations
    assertEquals(QR_CODE, qrCode.getBarcodeFormat());
    assertEquals(expectedRealmName, realm);
    assertEquals(expectedRealmName, issuer);
    assertEquals(testUser.getUsername(), user);

    // the actual test
    testOtp(type, algorithm, digits, period, counter, secret);
}