org.keycloak.models.UserCredentialModel Java Examples
The following examples show how to use
org.keycloak.models.UserCredentialModel.
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: UserCommands.java From keycloak with Apache License 2.0 | 6 votes |
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 #2
Source File: ApplianceBootstrap.java From keycloak with Apache License 2.0 | 6 votes |
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 #3
Source File: FineGrainAdminUnitTest.java From keycloak with Apache License 2.0 | 6 votes |
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 #4
Source File: UserMapStorage.java From keycloak with Apache License 2.0 | 6 votes |
@Override public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { if (editMode == UserStorageProvider.EditMode.READ_ONLY) { throw new ReadOnlyException("Federated storage is not writable"); } if (!(input instanceof UserCredentialModel)) { return false; } if (input.getType().equals(PasswordCredentialModel.TYPE)) { userPasswords.put(user.getUsername(), input.getChallengeResponse()); return true; } else { return false; } }
Example #5
Source File: SecretQuestionCredentialProvider.java From keycloak with Apache License 2.0 | 6 votes |
@Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { if (!(input instanceof UserCredentialModel)) { logger.debug("Expected instance of UserCredentialModel for CredentialInput"); return false; } if (!input.getType().equals(getType())) { return false; } String challengeResponse = input.getChallengeResponse(); if (challengeResponse == null) { return false; } CredentialModel credentialModel = getCredentialStore().getStoredCredentialById(realm, user, input.getCredentialId()); SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel); return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse); }
Example #6
Source File: RepresentationToModel.java From keycloak with Apache License 2.0 | 6 votes |
public static void createCredentials(UserRepresentation userRep, KeycloakSession session, RealmModel realm, UserModel user, boolean adminRequest) { convertDeprecatedCredentialsFormat(userRep); if (userRep.getCredentials() != null) { for (CredentialRepresentation cred : userRep.getCredentials()) { if (cred.getId() != null && session.userCredentialManager().getStoredCredentialById(realm, user, cred.getId()) != null) { continue; } if (cred.getValue() != null && !cred.getValue().isEmpty()) { RealmModel origRealm = session.getContext().getRealm(); try { session.getContext().setRealm(realm); session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false)); } catch (ModelException ex) { throw new PasswordPolicyNotMetException(ex.getMessage(), user.getUsername(), ex); } finally { session.getContext().setRealm(origRealm); } } else { session.userCredentialManager().createCredentialThroughProvider(realm, user, toModel(cred)); } } } }
Example #7
Source File: CredentialHelper.java From keycloak with Apache License 2.0 | 6 votes |
/** * Create OTP credential either in userStorage or local storage (Keycloak DB) * * @return true if credential was successfully created either in the user storage or Keycloak DB. False if error happened (EG. during HOTP validation) */ public static boolean createOTPCredential(KeycloakSession session, RealmModel realm, UserModel user, String totpCode, OTPCredentialModel credentialModel) { CredentialProvider otpCredentialProvider = session.getProvider(CredentialProvider.class, "keycloak-otp"); String totpSecret = credentialModel.getOTPSecretData().getValue(); UserCredentialModel otpUserCredential = new UserCredentialModel("", realm.getOTPPolicy().getType(), totpSecret); boolean userStorageCreated = session.userCredentialManager().updateCredential(realm, user, otpUserCredential); String credentialId = null; if (userStorageCreated) { logger.debugf("Created OTP credential for user '%s' in the user storage", user.getUsername()); } else { CredentialModel createdCredential = otpCredentialProvider.createCredential(realm, user, credentialModel); credentialId = createdCredential.getId(); } //If the type is HOTP, call verify once to consume the OTP used for registration and increase the counter. UserCredentialModel credential = new UserCredentialModel(credentialId, otpCredentialProvider.getType(), totpCode); return session.userCredentialManager().isValid(realm, user, credential); }
Example #8
Source File: MSADUserAccountControlStorageMapper.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void passwordUpdated(UserModel user, LDAPObject ldapUser, UserCredentialModel password) { logger.debugf("Going to update userAccountControl for ldap user '%s' after successful password update", ldapUser.getDn().toString()); // Normally it's read-only ldapUser.removeReadOnlyAttributeName(LDAPConstants.PWD_LAST_SET); ldapUser.setSingleAttribute(LDAPConstants.PWD_LAST_SET, "-1"); UserAccountControl control = getUserAccountControl(ldapUser); control.remove(UserAccountControl.PASSWD_NOTREQD); control.remove(UserAccountControl.PASSWORD_EXPIRED); if (user.isEnabled()) { control.remove(UserAccountControl.ACCOUNTDISABLE); } updateUserAccountControl(true, ldapUser, control); }
Example #9
Source File: BasicAuthOTPAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
private boolean checkOtp(AuthenticationFlowContext context, String otp) { OTPCredentialModel preferredCredential = getCredentialProvider(context.getSession()) .getDefaultCredential(context.getSession(), context.getRealm(), context.getUser()); boolean valid = getCredentialProvider(context.getSession()).isValid(context.getRealm(), context.getUser(), new UserCredentialModel(preferredCredential.getId(), getCredentialProvider(context.getSession()).getType(), otp)); if (!valid) { context.getEvent().user(context.getUser()).error(Errors.INVALID_USER_CREDENTIALS); if (context.getExecution().isRequired()){ Response challengeResponse = challenge(context, Messages.INVALID_TOTP); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse); } else { context.attempted(); } return false; } return true; }
Example #10
Source File: MSADLDSUserAccountControlStorageMapper.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void passwordUpdated(UserModel user, LDAPObject ldapUser, UserCredentialModel password) { logger.debugf("Going to update pwdLastSet for ldap user '%s' after successful password update", ldapUser.getDn().toString()); // Normally it's read-only ldapUser.removeReadOnlyAttributeName(LDAPConstants.PWD_LAST_SET); ldapUser.setSingleAttribute(LDAPConstants.PWD_LAST_SET, "-1"); if (user.isEnabled()) { // TODO: Use removeAttribute once available ldapUser.setSingleAttribute(LDAPConstants.MSDS_USER_ACCOUNT_DISABLED, "FALSE"); logger.debugf("Removing msDS-UserPasswordExpired of user '%s'", ldapUser.getDn().toString()); } ldapProvider.getLdapIdentityStore().update(ldapUser); }
Example #11
Source File: RemoteUserFederationProvider.java From keycloak-user-migration-provider with Apache License 2.0 | 6 votes |
@Override public boolean validCredentials(RealmModel realm, UserModel user, List<UserCredentialModel> input) { LOG.infof("Validating credentials for %s", user.getUsername()); if (input == null || input.isEmpty()) { throw new IllegalArgumentException("UserCredentialModel list is empty or null!"); } UserCredentialModel credentials = input.get(0); Response response = federatedUserService.validateLogin(user.getUsername(), new UserCredentialsDto(credentials.getValue())); boolean valid = HttpStatus.SC_OK == response.getStatus(); if (valid) { user.updateCredential(credentials); user.setFederationLink(null); } return valid; }
Example #12
Source File: ValidatePassword.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void authenticate(AuthenticationFlowContext context) { String password = retrievePassword(context); boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.password(password)); if (!valid) { context.getEvent().user(context.getUser()); context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials"); context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse); return; } context.success(); }
Example #13
Source File: RegistrationPassword.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void success(FormContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); String password = formData.getFirst(RegistrationPage.FIELD_PASSWORD); UserModel user = context.getUser(); try { context.getSession().userCredentialManager().updateCredential(context.getRealm(), user, UserCredentialModel.password(formData.getFirst("password"), false)); } catch (Exception me) { user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); } }
Example #14
Source File: HttpBasicAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
@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 #15
Source File: FineGrainAdminUnitTest.java From keycloak with Apache License 2.0 | 5 votes |
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 #16
Source File: UserPropertyFileStorage.java From keycloak with Apache License 2.0 | 5 votes |
@Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { if (!(input instanceof UserCredentialModel)) return false; if (input.getType().equals(PasswordCredentialModel.TYPE)) { String pw = (String)userPasswords.get(user.getUsername()); return pw != null && pw.equals(input.getChallengeResponse()); } else { return false; } }
Example #17
Source File: FailableHardcodedStorageProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { checkForceFail(); if (!(input instanceof UserCredentialModel)) return false; if (!user.getUsername().equals(username)) throw new RuntimeException("UNKNOWN USER!"); if (input.getType().equals(PasswordCredentialModel.TYPE)) { password = input.getChallengeResponse(); return true; } else { return false; } }
Example #18
Source File: UserMapStorage.java From keycloak with Apache License 2.0 | 5 votes |
@Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { // Test "instanceof PasswordUserCredentialModel" on purpose. We want to test that the backwards compatibility if (!(input instanceof PasswordUserCredentialModel)) { return false; } if (input.getType().equals(PasswordCredentialModel.TYPE)) { String pw = userPasswords.get(user.getUsername()); // Using "getValue" on purpose here, to test that backwards compatibility works as expected return pw != null && pw.equals(((UserCredentialModel) input).getValue()); } else { return false; } }
Example #19
Source File: AbstractUsernameFormAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
public boolean validatePassword(AuthenticationFlowContext context, UserModel user, MultivaluedMap<String, String> inputData, boolean clearUser) { String password = inputData.getFirst(CredentialRepresentation.PASSWORD); if (password == null || password.isEmpty()) { return badPasswordHandler(context, user, clearUser,true); } if (isTemporarilyDisabledByBruteForce(context, user)) return false; if (password != null && !password.isEmpty() && context.getSession().userCredentialManager().isValid(context.getRealm(), user, UserCredentialModel.password(password))) { return true; } else { return badPasswordHandler(context, user, clearUser,false); } }
Example #20
Source File: UserResource.java From keycloak with Apache License 2.0 | 5 votes |
/** * Set up a new password for the user. * * @param cred The representation must contain a rawPassword with the plain-text password */ @Path("reset-password") @PUT @Consumes(MediaType.APPLICATION_JSON) public void resetPassword(CredentialRepresentation cred) { auth.users().requireManage(user); if (cred == null || cred.getValue() == null) { throw new BadRequestException("No password provided"); } if (Validation.isBlank(cred.getValue())) { throw new BadRequestException("Empty password not allowed"); } try { session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false)); } catch (IllegalStateException ise) { throw new BadRequestException("Resetting to N old passwords is not allowed."); } catch (ReadOnlyException mre) { throw new BadRequestException("Can't reset password as account is read only"); } catch (ModelException e) { logger.warn("Could not update user password.", e); Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale()); throw new ErrorResponseException(e.getMessage(), MessageFormat.format(messages.getProperty(e.getMessage(), e.getMessage()), e.getParameters()), Status.BAD_REQUEST); } if (cred.isTemporary() != null && cred.isTemporary()) { user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); } else { // Remove a potentially existing UPDATE_PASSWORD action when explicitly assigning a non-temporary password. user.removeRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); } adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success(); }
Example #21
Source File: ClientResource.java From keycloak with Apache License 2.0 | 5 votes |
/** * Generate a new secret for the client * * @return */ @Path("client-secret") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public CredentialRepresentation regenerateSecret() { auth.clients().requireConfigure(client); logger.debug("regenerateSecret"); UserCredentialModel cred = KeycloakModelUtils.generateSecret(client); CredentialRepresentation rep = ModelToRepresentation.toRepresentation(cred); adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(rep).success(); return rep; }
Example #22
Source File: LDAPTestUtils.java From keycloak with Apache License 2.0 | 5 votes |
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 #23
Source File: TestingResourceProvider.java From keycloak with Apache License 2.0 | 5 votes |
@GET @Path("/valid-credentials") @Produces(MediaType.APPLICATION_JSON) public boolean validCredentials(@QueryParam("realmName") String realmName, @QueryParam("userName") String userName, @QueryParam("password") String password) { RealmModel realm = session.realms().getRealm(realmName); if (realm == null) return false; UserProvider userProvider = session.getProvider(UserProvider.class); UserModel user = userProvider.getUserByUsername(userName, realm); return session.userCredentialManager().isValid(realm, user, UserCredentialModel.password(password)); }
Example #24
Source File: ClientResource.java From keycloak with Apache License 2.0 | 5 votes |
/** * Get the client secret * * @return */ @Path("client-secret") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public CredentialRepresentation getClientSecret() { auth.clients().requireView(client); logger.debug("getClientSecret"); UserCredentialModel model = UserCredentialModel.secret(client.getSecret()); if (model == null) throw new NotFoundException("Client does not have a secret"); return ModelToRepresentation.toRepresentation(model); }
Example #25
Source File: KerberosFederationProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { if (!(input instanceof UserCredentialModel) || !PasswordCredentialModel.TYPE.equals(input.getType())) return false; if (kerberosConfig.getEditMode() == EditMode.READ_ONLY) { throw new ReadOnlyException("Can't change password in Keycloak database. Change password with your Kerberos server"); } return false; }
Example #26
Source File: DemoUserStorageProvider.java From keycloak-user-storage-provider-demo with Apache License 2.0 | 5 votes |
@Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { log.debugv("isValid user credential: userId={0}", user.getId()); if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) { return false; } UserCredentialModel cred = (UserCredentialModel) input; return repository.validateCredentials(user.getUsername(), cred.getChallengeResponse()); }
Example #27
Source File: DemoUserStorageProvider.java From keycloak-user-storage-provider-demo with Apache License 2.0 | 5 votes |
@Override public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { log.debugv("updating credential: realm={0} user={1}", realm.getId(), user.getUsername()); if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) { return false; } UserCredentialModel cred = (UserCredentialModel) input; return repository.updateCredentials(user.getUsername(), cred.getChallengeResponse()); }
Example #28
Source File: KeycloakSmsAuthenticator.java From keycloak-sms-authenticator with Eclipse Public License 2.0 | 5 votes |
private void storeSMSCode(AuthenticationFlowContext context, String code, Long expiringAt) { UserCredentialModel credentials = new UserCredentialModel(); credentials.setType(SMSAuthenticatorContstants.USR_CRED_MDL_SMS_CODE); credentials.setValue(code); context.getSession().users().updateCredential(context.getRealm(), context.getUser(), credentials); credentials.setType(SMSAuthenticatorContstants.USR_CRED_MDL_SMS_EXP_TIME); credentials.setValue((expiringAt).toString()); context.getSession().users().updateCredential(context.getRealm(), context.getUser(), credentials); }
Example #29
Source File: MSADUserAccountControlStorageMapper.java From keycloak with Apache License 2.0 | 5 votes |
@Override public LDAPOperationDecorator beforePasswordUpdate(UserModel user, LDAPObject ldapUser, UserCredentialModel password) { // Not apply policies if password is reset by admin (not by user himself) if (password.isAdminRequest()) { return null; } boolean applyDecorator = mapperModel.get(LDAP_PASSWORD_POLICY_HINTS_ENABLED, false); return applyDecorator ? new LDAPServerPolicyHintsDecorator() : null; }
Example #30
Source File: KerberosFederationProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public CredentialValidationOutput authenticate(RealmModel realm, CredentialInput input) { if (!(input instanceof UserCredentialModel)) return null; UserCredentialModel credential = (UserCredentialModel)input; if (credential.getType().equals(UserCredentialModel.KERBEROS)) { String spnegoToken = credential.getChallengeResponse(); SPNEGOAuthenticator spnegoAuthenticator = factory.createSPNEGOAuthenticator(spnegoToken, kerberosConfig); spnegoAuthenticator.authenticate(); Map<String, String> state = new HashMap<String, String>(); if (spnegoAuthenticator.isAuthenticated()) { String username = spnegoAuthenticator.getAuthenticatedUsername(); UserModel user = findOrCreateAuthenticatedUser(realm, username); if (user == null) { return CredentialValidationOutput.failed(); } else { String delegationCredential = spnegoAuthenticator.getSerializedDelegationCredential(); if (delegationCredential != null) { state.put(KerberosConstants.GSS_DELEGATION_CREDENTIAL, delegationCredential); } return new CredentialValidationOutput(user, CredentialValidationOutput.Status.AUTHENTICATED, state); } } else if (spnegoAuthenticator.getResponseToken() != null) { // Case when SPNEGO handshake requires multiple steps logger.tracef("SPNEGO Handshake will continue"); state.put(KerberosConstants.RESPONSE_TOKEN, spnegoAuthenticator.getResponseToken()); return new CredentialValidationOutput(null, CredentialValidationOutput.Status.CONTINUE, state); } else { logger.tracef("SPNEGO Handshake not successful"); return CredentialValidationOutput.failed(); } } else { return null; } }