Java Code Examples for org.keycloak.models.UserModel#setEnabled()

The following examples show how to use org.keycloak.models.UserModel#setEnabled() . 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: MSADLDSUserAccountControlStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean processAuthErrorCode(String errorCode, UserModel user) {
    logger.debugf("MSAD LDS Error code is '%s' after failed LDAP login of user '%s'", errorCode, user.getUsername());

    if (ldapProvider.getEditMode() == UserStorageProvider.EditMode.WRITABLE) {
        if (errorCode.equals("532") || errorCode.equals("773")) {
            // User needs to change his MSAD password. Allow him to login, but add UPDATE_PASSWORD required action
            if (!user.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_PASSWORD.name())) {
                user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
            }
            return true;
        } else if (errorCode.equals("533")) {
            // User is disabled in MSAD LDS. Set him to disabled in KC as well
            if (user.isEnabled()) {
                user.setEnabled(false);
            }
            return true;
        } else if (errorCode.equals("775")) {
            logger.warnf("Locked user '%s' attempt to login", user.getUsername());
        }
    }

    return false;
}
 
Example 2
Source File: MSADUserAccountControlStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean processAuthErrorCode(String errorCode, UserModel user) {
    logger.debugf("MSAD Error code is '%s' after failed LDAP login of user '%s'", errorCode, user.getUsername());

    if (ldapProvider.getEditMode() == UserStorageProvider.EditMode.WRITABLE) {
        if (errorCode.equals("532") || errorCode.equals("773")) {
            // User needs to change his MSAD password. Allow him to login, but add UPDATE_PASSWORD required action
            if (!user.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_PASSWORD.name())) {
                user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
            }
            return true;
        } else if (errorCode.equals("533")) {
            // User is disabled in MSAD. Set him to disabled in KC as well
            if (user.isEnabled()) {
                user.setEnabled(false);
            }
            return true;
        } else if (errorCode.equals("775")) {
            logger.warnf("Locked user '%s' attempt to login", user.getUsername());
        }
    }

    return false;
}
 
Example 3
Source File: KerberosFederationProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected UserModel importUserToKeycloak(RealmModel realm, String username) {
    // Just guessing email from kerberos realm
    String email = username + "@" + kerberosConfig.getKerberosRealm().toLowerCase();

    logger.debugf("Creating kerberos user: %s, email: %s to local Keycloak storage", username, email);
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEnabled(true);
    user.setEmail(email);
    user.setFederationLink(model.getId());
    user.setSingleAttribute(KERBEROS_PRINCIPAL, username + "@" + kerberosConfig.getKerberosRealm());

    if (kerberosConfig.isUpdateProfileFirstLogin()) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
    }

    return validate(realm, user);
}
 
Example 4
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setupDemo(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    realm.addRole("realm-role");
    ClientModel client = realm.addClient("sales-application");
    RoleModel clientAdmin = client.addRole("admin");
    client.addRole("leader-creator");
    client.addRole("viewLeads");
    GroupModel sales = realm.createGroup("sales");


    UserModel admin = session.users().addUser(realm, "salesManager");
    admin.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, admin, UserCredentialModel.password("password"));

    admin = session.users().addUser(realm, "sales-admin");
    admin.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, admin, UserCredentialModel.password("password"));

    UserModel user = session.users().addUser(realm, "salesman");
    user.setEnabled(true);
    user.joinGroup(sales);

    user = session.users().addUser(realm, "saleswoman");
    user.setEnabled(true);

}
 
Example 5
Source File: ApplianceBootstrap.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void createMasterRealmUser(String username, String password) {
    RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
    session.getContext().setRealm(realm);

    if (session.users().getUsersCount(realm) > 0) {
        throw new IllegalStateException("Can't create initial user as users already exists");
    }

    UserModel adminUser = session.users().addUser(realm, username);
    adminUser.setEnabled(true);

    UserCredentialModel usrCredModel = UserCredentialModel.password(password);
    session.userCredentialManager().updateCredential(realm, adminUser, usrCredModel);

    RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
    adminUser.grantRole(adminRole);
}
 
Example 6
Source File: UserCommands.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void createUsersInBatch(KeycloakSession session, int first, int count) {
    RealmModel realm = session.realms().getRealmByName(realmName);
    if (realm == null) {
        log.errorf("Unknown realm: %s", realmName);
        throw new HandledException();
    }

    Set<RoleModel> roles = findRoles(realm, roleNames);

    int last = first + count;
    for (int counter = first; counter < last; counter++) {
        String username = usernamePrefix + counter;
        UserModel user = session.users().addUser(realm, username);
        user.setEnabled(true);
        user.setEmail(username + "@keycloak.org");
        UserCredentialModel passwordCred = UserCredentialModel.password(password);
        session.userCredentialManager().updateCredential(realm, user, passwordCred);

        for (RoleModel role : roles) {
            user.grantRole(role);
        }
    }
    log.infof("Users from %s to %s created", usernamePrefix + first, usernamePrefix + (last - 1));
}
 
Example 7
Source File: FailableHardcodedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public UserModel getUserByUsername(String uname, RealmModel realm) {
    checkForceFail();
    if (!username.equals(uname)) return null;
    UserModel local = session.userLocalStorage().getUserByUsername(uname, realm);
    if (local != null && !model.getId().equals(local.getFederationLink())) {
        throw new RuntimeException("local storage has wrong federation link");
    }
    if (local != null) return new Delegate(local);
    local = session.userLocalStorage().addUser(realm, uname);
    local.setEnabled(true);
    local.setFirstName(first);
    local.setLastName(last);
    local.setEmail(email);
    local.setFederationLink(model.getId());
    for (String key : attributes.keySet()) {
        List<String> values = attributes.get(key);
        if (values == null) continue;
        local.setAttribute(key, values);
    }
    return new Delegate(local);
}
 
Example 8
Source File: PassThroughRegistration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    context.getEvent().detail(Details.USERNAME, username)
            .detail(Details.REGISTER_METHOD, "form")
            .detail(Details.EMAIL, email)
    ;
    UserModel user = context.getSession().users().addUser(context.getRealm(), username);
    user.setEnabled(true);

    user.setEmail(email);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    context.setUser(user);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId())
            .detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri())
            .detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
    context.success();
}
 
Example 9
Source File: LDAPTestUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static UserModel addLocalUser(KeycloakSession session, RealmModel realm, String username, String email, String password) {
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEmail(email);
    user.setEnabled(true);

    UserCredentialModel creds = UserCredentialModel.password(password);

    session.userCredentialManager().updateCredential(realm, user, creds);
    return user;
}
 
Example 10
Source File: RegistrationUserCreation.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String email = formData.getFirst(Validation.FIELD_EMAIL);
    String username = formData.getFirst(RegistrationPage.FIELD_USERNAME);
    if (context.getRealm().isRegistrationEmailAsUsername()) {
        username = formData.getFirst(RegistrationPage.FIELD_EMAIL);
    }
    context.getEvent().detail(Details.USERNAME, username)
            .detail(Details.REGISTER_METHOD, "form")
            .detail(Details.EMAIL, email)
    ;
    UserModel user = context.getSession().users().addUser(context.getRealm(), username);
    user.setEnabled(true);

    user.setEmail(email);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    AttributeFormDataProcessor.process(formData, context.getRealm(), user);
    context.setUser(user);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId())
            .detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri())
            .detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
}
 
Example 11
Source File: UserMapStorage.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserModel createUser(RealmModel realm, String username) {
    UserModel user;
    if (isImportEnabled()) {
        user = session.userLocalStorage().addUser(realm, username);
        user.setEnabled(true);
        user.setFederationLink(model.getId());
    } else {
        user = new AbstractUserAdapterFederatedStorage(session, realm, model) {
            @Override
            public String getUsername() {
                return username;
            }

            @Override
            public void setUsername(String innerUsername) {
                if (! Objects.equals(innerUsername, username)) {
                    throw new RuntimeException("Unsupported");
                }
            }

            @Override
            public void leaveGroup(GroupModel group) {
                UserMapStorage.this.leaveGroup(realm, getUsername(), group);
            }

            @Override
            public void joinGroup(GroupModel group) {
                UserMapStorage.this.joinGroup(realm, getUsername(), group);
            }

            @Override
            public String getFederationLink() {
                return model.getId();
            }
        };
    }

    return user;
}
 
Example 12
Source File: VirtualClientStorageProvider.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private UserModel createServiceAccountUser(RealmModel realm, ClientModel clientModel) {

        UserModel newServiceAccount = session.userLocalStorage().addUser(realm, "service-account-" + clientModel.getClientId());
        newServiceAccount.setEnabled(true);
        newServiceAccount.setServiceAccountClientLink(clientModel.getId());

        return newServiceAccount;
    }
 
Example 13
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void addDirectExchanger(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.addRole("example");
    AdminPermissionManagement management = AdminPermissions.management(session, realm);

    ClientModel directExchanger = realm.addClient("direct-exchanger");
    directExchanger.setName("direct-exchanger");
    directExchanger.setClientId("direct-exchanger");
    directExchanger.setPublicClient(false);
    directExchanger.setDirectAccessGrantsEnabled(true);
    directExchanger.setEnabled(true);
    directExchanger.setSecret("secret");
    directExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directExchanger.setFullScopeAllowed(false);

    // permission for client to client exchange to "target" client
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_SIGNED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_ENCRYPTED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_SIGNED_AND_ENCRYPTED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET), true);

    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonatorsDirect");
    clientImpersonateRep.addClient(directExchanger.getId());

    ResourceServer server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
    impersonatedUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password"));
    impersonatedUser.grantRole(exampleRole);
}
 
Example 14
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setup5152(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    RoleModel realmAdminRole = realmAdminClient.getRole(AdminRoles.REALM_ADMIN);

    UserModel realmUser = session.users().addUser(realm, "realm-admin");
    realmUser.grantRole(realmAdminRole);
    realmUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password"));
}
 
Example 15
Source File: IllegalAdminUpgradeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setupUsers(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    RealmModel master = session.realms().getRealmByName("master");
    ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    ClientModel realmMasterAdminClient = realm.getMasterAdminClient();
    RoleModel realmManageUsers = realmAdminClient.getRole(AdminRoles.MANAGE_USERS);
    RoleModel masterManageUsers = realmMasterAdminClient.getRole(AdminRoles.MANAGE_USERS);
    RoleModel masterMasterManageUSers = master.getMasterAdminClient().getRole(AdminRoles.MANAGE_USERS);

    UserModel realmUser = session.users().addUser(realm, "userAdmin");
    realmUser.grantRole(realmManageUsers);
    realmUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password"));

    UserModel masterUser = session.users().addUser(master, "userAdmin");
    masterUser.grantRole(masterManageUsers);
    masterUser.setEnabled(true);
    session.userCredentialManager().updateCredential(master, masterUser, UserCredentialModel.password("password"));

    UserModel masterAdmin = session.users().addUser(master, "masterAdmin");
    masterAdmin.grantRole(masterMasterManageUSers);
    masterAdmin.setEnabled(true);
    session.userCredentialManager().updateCredential(master, masterAdmin, UserCredentialModel.password("password"));

    UserModel user = session.users().addUser(master, "user");
    user.grantRole(masterManageUsers);
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(master, user, UserCredentialModel.password("password"));

    user = session.users().addUser(realm, "user");
    user.grantRole(realmManageUsers);
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
}
 
Example 16
Source File: RemoteUserFederationProvider.java    From keycloak-user-migration-provider with Apache License 2.0 5 votes vote down vote up
private UserModel createUserModel(RealmModel realm, String rawUsername) throws NotFoundException {

        String username = rawUsername.toLowerCase().trim();
        FederatedUserModel remoteUser = federatedUserService.getUserDetails(username);
        LOG.infof("Creating user model for: %s", username);
        UserModel userModel = session.userStorage().addUser(realm, username);

        if (!username.equals(remoteUser.getEmail())) {
            throw new IllegalStateException(String.format("Local and remote users differ: [%s != %s]", username, remoteUser.getUsername()));
        }

        userModel.setFederationLink(model.getId());
        userModel.setEnabled(remoteUser.isEnabled());
        userModel.setEmail(username);
        userModel.setEmailVerified(remoteUser.isEmailVerified());
        userModel.setFirstName(remoteUser.getFirstName());
        userModel.setLastName(remoteUser.getLastName());

        if (remoteUser.getAttributes() != null) {
            Map<String, List<String>> attributes = remoteUser.getAttributes();
            for (String attributeName : attributes.keySet())
                userModel.setAttribute(attributeName, attributes.get(attributeName));
        }

        if (remoteUser.getRoles() != null) {
            for (String role : remoteUser.getRoles()) {
                RoleModel roleModel = realm.getRole(role);
                if (roleModel != null) {
                    userModel.grantRole(roleModel);
                    LOG.infof("Granted user %s, role %s", username, role);
                }
            }
        }

        return userModel;
    }
 
Example 17
Source File: ClientTokenExchangeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static void addDirectExchanger(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.addRole("example");
    AdminPermissionManagement management = AdminPermissions.management(session, realm);

    ClientModel target = realm.addClient("target");
    target.setName("target");
    target.setClientId("target");
    target.setDirectAccessGrantsEnabled(true);
    target.setEnabled(true);
    target.setSecret("secret");
    target.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    target.setFullScopeAllowed(false);
    target.addScopeMapping(exampleRole);

    ClientModel directExchanger = realm.addClient("direct-exchanger");
    directExchanger.setName("direct-exchanger");
    directExchanger.setClientId("direct-exchanger");
    directExchanger.setPublicClient(false);
    directExchanger.setDirectAccessGrantsEnabled(true);
    directExchanger.setEnabled(true);
    directExchanger.setSecret("secret");
    directExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directExchanger.setFullScopeAllowed(false);

    // permission for client to client exchange to "target" client
    management.clients().setPermissionsEnabled(target, true);

    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonatorsDirect");
    clientImpersonateRep.addClient(directExchanger.getId());

    ResourceServer server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
    impersonatedUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password"));
    impersonatedUser.grantRole(exampleRole);
}
 
Example 18
Source File: ClientTokenExchangeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void setupRealm(KeycloakSession session) {
    addDirectExchanger(session);

    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.getRole("example");

    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    ClientModel target = realm.getClientByClientId("target");
    assertNotNull(target);

    RoleModel impersonateRole = management.getRealmManagementClient().getRole(ImpersonationConstants.IMPERSONATION_ROLE);

    ClientModel clientExchanger = realm.addClient("client-exchanger");
    clientExchanger.setClientId("client-exchanger");
    clientExchanger.setPublicClient(false);
    clientExchanger.setDirectAccessGrantsEnabled(true);
    clientExchanger.setEnabled(true);
    clientExchanger.setSecret("secret");
    clientExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    clientExchanger.setFullScopeAllowed(false);
    clientExchanger.addScopeMapping(impersonateRole);
    clientExchanger.addProtocolMapper(UserSessionNoteMapper.createUserSessionNoteMapper(IMPERSONATOR_ID));
    clientExchanger.addProtocolMapper(UserSessionNoteMapper.createUserSessionNoteMapper(IMPERSONATOR_USERNAME));

    ClientModel illegal = realm.addClient("illegal");
    illegal.setClientId("illegal");
    illegal.setPublicClient(false);
    illegal.setDirectAccessGrantsEnabled(true);
    illegal.setEnabled(true);
    illegal.setSecret("secret");
    illegal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    illegal.setFullScopeAllowed(false);

    ClientModel legal = realm.addClient("legal");
    legal.setClientId("legal");
    legal.setPublicClient(false);
    legal.setDirectAccessGrantsEnabled(true);
    legal.setEnabled(true);
    legal.setSecret("secret");
    legal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    legal.setFullScopeAllowed(false);

    ClientModel directLegal = realm.addClient("direct-legal");
    directLegal.setClientId("direct-legal");
    directLegal.setPublicClient(false);
    directLegal.setDirectAccessGrantsEnabled(true);
    directLegal.setEnabled(true);
    directLegal.setSecret("secret");
    directLegal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directLegal.setFullScopeAllowed(false);

    ClientModel directPublic = realm.addClient("direct-public");
    directPublic.setClientId("direct-public");
    directPublic.setPublicClient(true);
    directPublic.setDirectAccessGrantsEnabled(true);
    directPublic.setEnabled(true);
    directPublic.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directPublic.setFullScopeAllowed(false);

    ClientModel directNoSecret = realm.addClient("direct-no-secret");
    directNoSecret.setClientId("direct-no-secret");
    directNoSecret.setPublicClient(false);
    directNoSecret.setDirectAccessGrantsEnabled(true);
    directNoSecret.setEnabled(true);
    directNoSecret.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directNoSecret.setFullScopeAllowed(false);

    // permission for client to client exchange to "target" client
    ClientPolicyRepresentation clientRep = new ClientPolicyRepresentation();
    clientRep.setName("to");
    clientRep.addClient(clientExchanger.getId());
    clientRep.addClient(legal.getId());
    clientRep.addClient(directLegal.getId());

    ResourceServer server = management.realmResourceServer();
    Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
    management.clients().exchangeToPermission(target).addAssociatedPolicy(clientPolicy);

    // permission for user impersonation for a client

    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonators");
    clientImpersonateRep.addClient(directLegal.getId());
    clientImpersonateRep.addClient(directPublic.getId());
    clientImpersonateRep.addClient(directNoSecret.getId());
    server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    UserModel user = session.users().addUser(realm, "user");
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
    user.grantRole(exampleRole);
    user.grantRole(impersonateRole);

    UserModel bad = session.users().addUser(realm, "bad-impersonator");
    bad.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, bad, UserCredentialModel.password("password"));
}
 
Example 19
Source File: IdpCreateUserIfUniqueAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {

    KeycloakSession session = context.getSession();
    RealmModel realm = context.getRealm();

    if (context.getAuthenticationSession().getAuthNote(EXISTING_USER_INFO) != null) {
        context.attempted();
        return;
    }

    String username = getUsername(context, serializedCtx, brokerContext);
    if (username == null) {
        ServicesLogger.LOGGER.resetFlow(realm.isRegistrationEmailAsUsername() ? "Email" : "Username");
        context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        context.resetFlow();
        return;
    }

    ExistingUserInfo duplication = checkExistingUser(context, username, serializedCtx, brokerContext);

    if (duplication == null) {
        logger.debugf("No duplication detected. Creating account for user '%s' and linking with identity provider '%s' .",
                username, brokerContext.getIdpConfig().getAlias());

        UserModel federatedUser = session.users().addUser(realm, username);
        federatedUser.setEnabled(true);
        federatedUser.setEmail(brokerContext.getEmail());
        federatedUser.setFirstName(brokerContext.getFirstName());
        federatedUser.setLastName(brokerContext.getLastName());

        for (Map.Entry<String, List<String>> attr : serializedCtx.getAttributes().entrySet()) {
            federatedUser.setAttribute(attr.getKey(), attr.getValue());
        }

        AuthenticatorConfigModel config = context.getAuthenticatorConfig();
        if (config != null && Boolean.parseBoolean(config.getConfig().get(IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION))) {
            logger.debugf("User '%s' required to update password", federatedUser.getUsername());
            federatedUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
        }

        userRegisteredSuccess(context, federatedUser, serializedCtx, brokerContext);

        context.setUser(federatedUser);
        context.getAuthenticationSession().setAuthNote(BROKER_REGISTERED_NEW_USER, "true");
        context.success();
    } else {
        logger.debugf("Duplication detected. There is already existing user with %s '%s' .",
                duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue());

        // Set duplicated user, so next authenticators can deal with it
        context.getAuthenticationSession().setAuthNote(EXISTING_USER_INFO, duplication.serialize());
        //Only show error message if the authenticator was required
        if (context.getExecution().isRequired()) {
            Response challengeResponse = context.form()
                    .setError(Messages.FEDERATED_IDENTITY_EXISTS, duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .createErrorPage(Response.Status.CONFLICT);
            context.challenge(challengeResponse);
            context.getEvent()
                    .user(duplication.getExistingUserId())
                    .detail("existing_" + duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .removeDetail(Details.AUTH_METHOD)
                    .removeDetail(Details.AUTH_TYPE)
                    .error(Errors.FEDERATED_IDENTITY_EXISTS);
        } else {
            context.attempted();
        }
    }
}
 
Example 20
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
    convertDeprecatedSocialProviders(userRep);

    // Import users just to user storage. Don't federate
    UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
    user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
    user.setCreatedTimestamp(userRep.getCreatedTimestamp());
    user.setEmail(userRep.getEmail());
    if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
    user.setFirstName(userRep.getFirstName());
    user.setLastName(userRep.getLastName());
    user.setFederationLink(userRep.getFederationLink());
    if (userRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
            List<String> value = entry.getValue();
            if (value != null) {
                user.setAttribute(entry.getKey(), new ArrayList<>(value));
            }
        }
    }
    if (userRep.getRequiredActions() != null) {
        for (String requiredAction : userRep.getRequiredActions()) {
            try {
                user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction.toUpperCase()));
            } catch (IllegalArgumentException iae) {
                user.addRequiredAction(requiredAction);
            }
        }
    }
    createCredentials(userRep, session, newRealm, user, false);
    createFederatedIdentities(userRep, session, newRealm, user);
    createRoleMappings(userRep, user, newRealm);
    if (userRep.getClientConsents() != null) {
        for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
            UserConsentModel consentModel = toModel(newRealm, consentRep);
            session.users().addConsent(newRealm, user.getId(), consentModel);
        }
    }

    if (userRep.getNotBefore() != null) {
        session.users().setNotBeforeForUser(newRealm, user, userRep.getNotBefore());
    }

    if (userRep.getServiceAccountClientId() != null) {
        String clientId = userRep.getServiceAccountClientId();
        ClientModel client = newRealm.getClientByClientId(clientId);
        if (client == null) {
            throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
        }
        user.setServiceAccountClientLink(client.getId());
    }
    createGroups(userRep, newRealm, user);
    return user;
}