org.keycloak.models.RealmModel Java Examples

The following examples show how to use org.keycloak.models.RealmModel. 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: TotpUtils.java    From keycloak with Apache License 2.0 8 votes vote down vote up
public static String qrCode(String totpSecret, RealmModel realm, UserModel user) {
    try {
        String keyUri = realm.getOTPPolicy().getKeyURI(realm, user, totpSecret);

        int width = 246;
        int height = 246;

        QRCodeWriter writer = new QRCodeWriter();
        final BitMatrix bitMatrix = writer.encode(keyUri, BarcodeFormat.QR_CODE, width, height);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", bos);
        bos.close();

        return Base64.encodeBytes(bos.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: DefaultBruteForceProtector.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isTemporarilyDisabled(KeycloakSession session, RealmModel realm, UserModel user) {
    UserLoginFailureModel failure = session.sessions().getUserLoginFailure(realm, user.getId());

    if (failure != null) {
        int currTime = (int) (Time.currentTimeMillis() / 1000);
        int failedLoginNotBefore = failure.getFailedLoginNotBefore();
        if (currTime < failedLoginNotBefore) {
            logger.debugv("Current: {0} notBefore: {1}", currTime, failedLoginNotBefore);
            return true;
        }
    }


    return false;
}
 
Example #3
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void preprocessFederatedIdentity(KeycloakSession session, RealmModel realm, BrokeredIdentityContext context) {
    AuthenticationSessionModel authenticationSession = session.getContext().getAuthenticationSession();
    
    if (authenticationSession == null) {
        // no interacting with the brokered OP, likely doing token exchanges
        return;
    }

    String nonce = (String) context.getContextData().get(BROKER_NONCE_PARAM);

    if (nonce == null) {
        throw new IdentityBrokerException("OpenID Provider [" + getConfig().getProviderId() + "] did not return a nonce");
    }

    String expectedNonce = authenticationSession.getClientNote(BROKER_NONCE_PARAM);

    if (!nonce.equals(expectedNonce)) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid nonce", Response.Status.BAD_REQUEST);
    }
}
 
Example #4
Source File: DefaultKeyManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
@Deprecated
public List<RsaKeyMetadata> getRsaKeys(RealmModel realm) {
    List<RsaKeyMetadata> keys = new LinkedList<>();
    for (KeyWrapper key : getKeys(realm, KeyUse.SIG, Algorithm.RS256)) {
        RsaKeyMetadata m = new RsaKeyMetadata();
        m.setCertificate(key.getCertificate());
        m.setPublicKey((PublicKey) key.getPublicKey());
        m.setKid(key.getKid());
        m.setProviderId(key.getProviderId());
        m.setProviderPriority(key.getProviderPriority());
        m.setStatus(key.getStatus());

        keys.add(m);
    }
    return keys;
}
 
Example #5
Source File: MultipleStepsExportProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    final RealmsHolder holder = new RealmsHolder();

    KeycloakModelUtils.runJobInTransaction(factory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            List<RealmModel> realms = session.realms().getRealms();
            holder.realms = realms;
        }

    });

    for (RealmModel realm : holder.realms) {
        exportRealmImpl(factory, realm.getName());
    }
}
 
Example #6
Source File: ConcurrentTransactionsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void tearDownRealm(KeycloakSession session, String user1, String user2) {
    KeycloakSession currentSession = session;

    RealmModel realm = currentSession.realms().getRealmByName("original");

    UserModel realmUser1 = currentSession.users().getUserByUsername(user1, realm);
    UserModel realmUser2 = currentSession.users().getUserByUsername(user2, realm);

    UserManager um = new UserManager(currentSession);
    if (realmUser1 != null) {
        um.removeUser(realm, realmUser1);
    }
    if (realmUser2 != null) {
        um.removeUser(realm, realmUser2);
    }

    Assert.assertTrue(currentSession.realms().removeRealm(realm.getId()));
    Assert.assertThat(currentSession.realms().getRealm(realm.getId()), is(nullValue()));
}
 
Example #7
Source File: ResourceAdminManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void logoutUserSessions(RealmModel realm, List<UserSessionModel> userSessions) {
    // Map from "app" to clientSessions for this app
    MultivaluedHashMap<String, AuthenticatedClientSessionModel> clientSessions = new MultivaluedHashMap<>();
    for (UserSessionModel userSession : userSessions) {
        putClientSessions(clientSessions, userSession);
    }

    logger.debugv("logging out {0} resources ", clientSessions.size());
    //logger.infov("logging out resources: {0}", clientSessions);

    for (Map.Entry<String, List<AuthenticatedClientSessionModel>> entry : clientSessions.entrySet()) {
        if (entry.getValue().size() == 0) {
            continue;
        }
        logoutClientSessions(realm, entry.getValue().get(0).getClient(), entry.getValue());
    }
}
 
Example #8
Source File: PolicyEvaluationCompositeRoleTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setup(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);

    session.getContext().setRealm(realm);

    ClientModel client = session.realms().addClient(realm, "myclient");
    RoleModel role1 = client.addRole("client-role1");


    AuthorizationProviderFactory factory = (AuthorizationProviderFactory)session.getKeycloakSessionFactory().getProviderFactory(AuthorizationProvider.class);
    AuthorizationProvider authz = factory.create(session, realm);
    ResourceServer resourceServer = authz.getStoreFactory().getResourceServerStore().create(client.getId());
    Policy policy = createRolePolicy(authz, resourceServer, role1);

    Scope scope = authz.getStoreFactory().getScopeStore().create("myscope", resourceServer);
    Resource resource = authz.getStoreFactory().getResourceStore().create("myresource", resourceServer, resourceServer.getId());
    addScopePermission(authz, resourceServer, "mypermission", resource, scope, policy);

    RoleModel composite = realm.addRole("composite");
    composite.addCompositeRole(role1);

    UserModel user = session.users().addUser(realm, "user");
    user.grantRole(composite);
}
 
Example #9
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static Response finishBrowserLogout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers) {
    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);

    checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);

    expireIdentityCookie(realm, uriInfo, connection);
    expireRememberMeCookie(realm, uriInfo, connection);
    userSession.setState(UserSessionModel.State.LOGGED_OUT);
    String method = userSession.getNote(KEYCLOAK_LOGOUT_PROTOCOL);
    EventBuilder event = new EventBuilder(realm, session, connection);
    LoginProtocol protocol = session.getProvider(LoginProtocol.class, method);
    protocol.setRealm(realm)
            .setHttpHeaders(headers)
            .setUriInfo(uriInfo)
            .setEventBuilder(event);
    Response response = protocol.finishLogout(userSession);
    session.sessions().removeUserSession(realm, userSession);
    session.authenticationSessions().removeRootAuthenticationSession(realm, logoutAuthSession.getParentSession());
    return response;
}
 
Example #10
Source File: LDAPNoMSADTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void afterImportTestRealm() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();

        LDAPTestUtils.addLocalUser(session, appRealm, "marykeycloak", "[email protected]", "password-app");

        LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());

        // Delete all LDAP users and add some new for testing
        LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
        LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);

        LDAPObject john = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnkeycloak", "John", "Doe", "[email protected]", null, "1234");
        LDAPTestUtils.updateLDAPPassword(ldapFedProvider, john, "Password1");

        LDAPObject existing = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "existing", "Existing", "Foo", "[email protected]", null, "5678");

        appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
    });
}
 
Example #11
Source File: DefaultLocaleSelectorProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Locale getUserLocale(RealmModel realm, AuthenticationSessionModel session, UserModel user, HttpHeaders requestHeaders) {
    Locale locale;

    locale = getUserSelectedLocale(realm, session);
    if (locale != null) {
        return locale;
    }

    locale = getUserProfileSelection(realm, user);
    if (locale != null) {
        return locale;
    }

    locale = getClientSelectedLocale(realm, session);
    if (locale != null) {
        return locale;
    }

    locale = getLocaleCookieSelection(realm, requestHeaders);
    if (locale != null) {
        return locale;
    }

    locale = getAcceptLanguageHeaderLocale(realm, requestHeaders);
    if (locale != null) {
        return locale;
    }

    return null;
}
 
Example #12
Source File: LDAPGroupMapperSyncTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel realm = ctx.getRealm();

        List<GroupModel> kcGroups = realm.getTopLevelGroups();
        for (GroupModel kcGroup : kcGroups) {
            realm.removeGroup(kcGroup);
        }
    });
}
 
Example #13
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) {
    RoleModel role = roleRep.getId() != null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName());
    if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription());
    if (roleRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> attribute : roleRep.getAttributes().entrySet()) {
            role.setAttribute(attribute.getKey(), attribute.getValue());
        }
    }
}
 
Example #14
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void importGroups(RealmModel realm, RealmRepresentation rep) {
    List<GroupRepresentation> groups = rep.getGroups();
    if (groups == null) return;

    GroupModel parent = null;
    for (GroupRepresentation group : groups) {
        importGroup(realm, parent, group);
    }
}
 
Example #15
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void dettachClientSession(UserSessionProvider sessions, RealmModel realm, AuthenticatedClientSessionModel clientSession) {
    UserSessionModel userSession = clientSession.getUserSession();
    if (userSession == null) {
        return;
    }

    clientSession.detachFromUserSession();

    // TODO: Might need optimization to prevent loading client sessions from cache in getAuthenticatedClientSessions()
    if (userSession.getAuthenticatedClientSessions().isEmpty()) {
        sessions.removeUserSession(realm, userSession);
    }
}
 
Example #16
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public  void testCreateSessions(KeycloakSession session) {
    int started = Time.currentTime();
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);

    assertSession(session.sessions().getUserSession(realm, sessions[0].getId()), session.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party");
    assertSession(session.sessions().getUserSession(realm, sessions[1].getId()), session.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app");
    assertSession(session.sessions().getUserSession(realm, sessions[2].getId()), session.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app");
}
 
Example #17
Source File: MigrateTo4_2_0.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
    // Set default priority of required actions in alphabetical order
    List<RequiredActionProviderModel> actions = realm.getRequiredActionProviders().stream()
            .sorted(comparing(RequiredActionProviderModel::getName)).collect(Collectors.toList());
    int priority = 10;
    for (RequiredActionProviderModel model : actions) {
        LOG.debugf("Setting priority '%d' for required action '%s' in realm '%s'", priority, model.getAlias(),
                realm.getName());
        model.setPriority(priority);
        priority += 10;

        // Save
        realm.updateRequiredActionProvider(model);
    }
}
 
Example #18
Source File: DefaultClientScopes.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param session
 * @param realm
 * @param addScopesToExistingClients true when creating new realm. False when migrating from previous version
 */
public static void createDefaultClientScopes(KeycloakSession session, RealmModel realm, boolean addScopesToExistingClients) {
    List<ProviderFactory> loginProtocolFactories = session.getKeycloakSessionFactory().getProviderFactories(LoginProtocol.class);
    for (ProviderFactory factory : loginProtocolFactories) {
        LoginProtocolFactory lpf = (LoginProtocolFactory) factory;
        lpf.createDefaultClientScopes(realm, addScopesToExistingClients);
    }
}
 
Example #19
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(final AuthenticationFlowContext context) {
    final HttpRequest httpRequest = context.getHttpRequest();
    final HttpHeaders httpHeaders = httpRequest.getHttpHeaders();
    final String[] usernameAndPassword = getUsernameAndPassword(httpHeaders);

    context.attempted();

    if (usernameAndPassword != null) {
        final RealmModel realm = context.getRealm();
        final String username = usernameAndPassword[0];
        final UserModel user = context.getSession().users().getUserByUsername(username, realm);

        // to allow success/failure logging for brute force
        context.getEvent().detail(Details.USERNAME, username);
        context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

        if (user != null) {
            final String password = usernameAndPassword[1];
            final boolean valid = context.getSession().userCredentialManager().isValid(realm, user, UserCredentialModel.password(password));

            if (valid) {
                if (isTemporarilyDisabledByBruteForce(context, user)) {
                    userDisabledAction(context, realm, user, Errors.USER_TEMPORARILY_DISABLED);
                } else if (user.isEnabled()) {
                    userSuccessAction(context, user);
                } else {
                    userDisabledAction(context, realm, user, Errors.USER_DISABLED);
                }
            } else {
                notValidCredentialsAction(context, realm, user);
            }
        } else {
            nullUserAction(context, realm, username);
        }
    }
}
 
Example #20
Source File: BackwardsCompatibilityUserStorage.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
    // Always assume that password is supported
    if (CredentialModel.PASSWORD.equals(credentialType)) return true;
    MyUser myUser = getMyUser(user);
    if (myUser == null) return false;

    if (isOTPType(credentialType) && myUser.otp != null) {
        return true;
    } else {
        log.infof("Not supported credentialType '%s' for user '%s'", credentialType, user.getUsername());
        return false;
    }
}
 
Example #21
Source File: ApplianceBootstrap.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean createMasterRealm() {
    if (!isNewInstall()) {
        throw new IllegalStateException("Can't create default realm as realms already exists");
    }

    String adminRealmName = Config.getAdminRealm();
    ServicesLogger.LOGGER.initializingAdminRealm(adminRealmName);

    RealmManager manager = new RealmManager(session);
    RealmModel realm = manager.createRealm(adminRealmName, adminRealmName);
    realm.setName(adminRealmName);
    realm.setDisplayName(Version.NAME);
    realm.setDisplayNameHtml(Version.NAME_HTML);
    realm.setEnabled(true);
    realm.addRequiredCredential(CredentialRepresentation.PASSWORD);
    realm.setSsoSessionIdleTimeout(1800);
    realm.setAccessTokenLifespan(60);
    realm.setAccessTokenLifespanForImplicitFlow(Constants.DEFAULT_ACCESS_TOKEN_LIFESPAN_FOR_IMPLICIT_FLOW_TIMEOUT);
    realm.setSsoSessionMaxLifespan(36000);
    realm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
    // KEYCLOAK-7688 Offline Session Max for Offline Token
    realm.setOfflineSessionMaxLifespanEnabled(false);
    realm.setOfflineSessionMaxLifespan(Constants.DEFAULT_OFFLINE_SESSION_MAX_LIFESPAN);
    realm.setAccessCodeLifespan(60);
    realm.setAccessCodeLifespanUserAction(300);
    realm.setAccessCodeLifespanLogin(1800);
    realm.setSslRequired(SslRequired.EXTERNAL);
    realm.setRegistrationAllowed(false);
    realm.setRegistrationEmailAsUsername(false);

    session.getContext().setRealm(realm);

    return true;
}
 
Example #22
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public int getUsersCount(RealmModel realm, Set<String> groupIds) {
    if (groupIds == null || groupIds.isEmpty()) {
        return 0;
    }

    TypedQuery<Long> query = em.createNamedQuery("userCountInGroups", Long.class);
    query.setParameter("realmId", realm.getId());
    query.setParameter("groupIds", groupIds);
    Long count = query.getSingleResult();

    return count.intValue();
}
 
Example #23
Source File: InfinispanUserSessionProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
UserSessionEntity getUserSessionEntity(RealmModel realm, UserSessionModel userSession, boolean offline) {
    if (userSession instanceof UserSessionAdapter) {
        if (!userSession.getRealm().equals(realm)) return null;
        return ((UserSessionAdapter) userSession).getEntity();
    } else {
        return getUserSessionEntity(realm, userSession.getId(), offline);
    }
}
 
Example #24
Source File: EventBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public EventBuilder(RealmModel realm, KeycloakSession session, ClientConnection clientConnection) {
    this.realm = realm;

    event = new Event();

    if (realm.isEventsEnabled()) {
        EventStoreProvider store = session.getProvider(EventStoreProvider.class);
        if (store != null) {
            this.store = store;
        } else {
            log.error("Events enabled, but no event store provider configured");
        }
    }

    if (realm.getEventsListeners() != null && !realm.getEventsListeners().isEmpty()) {
        this.listeners = new LinkedList<>();
        for (String id : realm.getEventsListeners()) {
            EventListenerProvider listener = session.getProvider(EventListenerProvider.class, id);
            if (listener != null) {
                listeners.add(listener);
            } else {
                log.error("Event listener '" + id + "' registered, but provider not found");
            }
        }
    }

    realm(realm);
    ipAddress(clientConnection.getRemoteAddr());
}
 
Example #25
Source File: LdapManyGroupsInitializerCommand.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ComponentModel getMapperModel(RealmModel realm, ComponentModel ldapModel, String mapperName) {
    List<ComponentModel> ldapMappers = realm.getComponents(ldapModel.getId(), LDAPStorageMapper.class.getName());
    Optional<ComponentModel> optional = ldapMappers.stream().filter((ComponentModel mapper) -> {
        return mapper.getName().equals(mapperName);
    }).findFirst();

    if (!optional.isPresent()) {
        log.errorf("Not present LDAP mapper called '%s'", mapperName);
        throw new HandledException();
    }

    return optional.get();
}
 
Example #26
Source File: UserSessionManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Set<ClientModel> findClientsWithOfflineToken(RealmModel realm, UserModel user) {
    List<UserSessionModel> userSessions = kcSession.sessions().getOfflineUserSessions(realm, user);
    Set<ClientModel> clients = new HashSet<>();
    for (UserSessionModel userSession : userSessions) {
        Set<String> clientIds = userSession.getAuthenticatedClientSessions().keySet();
        for (String clientUUID : clientIds) {
            ClientModel client = realm.getClientById(clientUUID);
            clients.add(client);
        }
    }
    return clients;
}
 
Example #27
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
    Map<String, String> attributes = new HashMap<>();
    attributes.put(UserModel.SEARCH, search);
    session.setAttribute(UserModel.INCLUDE_SERVICE_ACCOUNT, false);
    return searchForUser(attributes, realm, firstResult, maxResults);
}
 
Example #28
Source File: DummyUserFederationProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) {
    if (user.getUsername().equals("test-user")) {
        if (PasswordCredentialModel.TYPE.equals(credentialInput.getType())) {
            return HARDCODED_PASSWORD.equals(credentialInput.getChallengeResponse());
        } else if (OTPCredentialModel.TYPE.equals(credentialInput.getType())) {
            return HARDCODED_OTP.equals(credentialInput.getChallengeResponse());
        }
    }
    return false;
}
 
Example #29
Source File: VirtualClientModelGenerator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
VirtualClientModel createVirtualModel(String id, String clientId, RealmModel realm) {
    return createVirtualModel(id, clientId, realm, modelAttributes -> {
        modelAttributes.put("publicClient", false);
        modelAttributes.put("directAccessGrantsEnabled", true);
        modelAttributes.put("standardFlowEnabled", false);
    });
}
 
Example #30
Source File: ClientStorageManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientStorageProvider getStorageProvider(KeycloakSession session, RealmModel realm, String componentId) {
    ComponentModel model = realm.getComponent(componentId);
    if (model == null) return null;
    ClientStorageProviderModel storageModel = new ClientStorageProviderModel(model);
    ClientStorageProviderFactory factory = (ClientStorageProviderFactory)session.getKeycloakSessionFactory().getProviderFactory(ClientStorageProvider.class, model.getProviderId());
    if (factory == null) {
        throw new ModelException("Could not find ClientStorageProviderFactory for: " + model.getProviderId());
    }
    return getStorageProviderInstance(session, storageModel, factory);
}