Java Code Examples for org.keycloak.models.UserModel#getUsername()
The following examples show how to use
org.keycloak.models.UserModel#getUsername() .
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: 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 2
Source File: CachedUser.java From keycloak with Apache License 2.0 | 6 votes |
public CachedUser(Long revision, RealmModel realm, UserModel user, int notBefore) { super(revision, user.getId()); this.realm = realm.getId(); this.username = user.getUsername(); this.createdTimestamp = user.getCreatedTimestamp(); this.email = user.getEmail(); this.emailVerified = user.isEmailVerified(); this.enabled = user.isEnabled(); this.federationLink = user.getFederationLink(); this.serviceAccountClientLink = user.getServiceAccountClientLink(); this.notBefore = notBefore; this.requiredActions = new DefaultLazyLoader<>(UserModel::getRequiredActions, Collections::emptySet); this.attributes = new DefaultLazyLoader<>(userModel -> new MultivaluedHashMap<>(userModel.getAttributes()), MultivaluedHashMap::new); this.roleMappings = new DefaultLazyLoader<>(userModel -> userModel.getRoleMappings().stream().map(RoleModel::getId).collect(Collectors.toSet()), Collections::emptySet); this.groups = new DefaultLazyLoader<>(userModel -> userModel.getGroups().stream().map(GroupModel::getId).collect(Collectors.toCollection(LinkedHashSet::new)), LinkedHashSet::new); }
Example 3
Source File: AbstractIdpAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
public static UserModel getExistingUser(KeycloakSession session, RealmModel realm, AuthenticationSessionModel authSession) { String existingUserId = authSession.getAuthNote(EXISTING_USER_INFO); if (existingUserId == null) { throw new AuthenticationFlowException("Unexpected state. There is no existing duplicated user identified in ClientSession", AuthenticationFlowError.INTERNAL_ERROR); } ExistingUserInfo duplication = ExistingUserInfo.deserialize(existingUserId); UserModel existingUser = session.users().getUserById(duplication.getExistingUserId(), realm); if (existingUser == null) { throw new AuthenticationFlowException("User with ID '" + existingUserId + "' not found.", AuthenticationFlowError.INVALID_USER); } if (!existingUser.isEnabled()) { throw new AuthenticationFlowException("User with ID '" + existingUserId + "', username '" + existingUser.getUsername() + "' disabled.", AuthenticationFlowError.USER_DISABLED); } return existingUser; }
Example 4
Source File: ThirdPartyMfaAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 5 votes |
@Override public void authenticate(AuthenticationFlowContext context) { RealmModel realm = context.getRealm(); UserModel user = context.getUser(); String username = user.getUsername(); log.infof("Request MFA for User. username=%s", username); String existingMfaSessionMarker = session.sessions().getUserSessions(realm, user).stream() // TODO ensure user comes from the same device .filter(us -> us.getNote(MFA_SESSION_MARKER_KEY) != null) .map(us -> us.getNote(MFA_SESSION_MARKER_KEY)) .findFirst() .orElse(null); if (existingMfaSessionMarker != null) { // There is already an existing user session that was authenticated via MFA // TODO check max time since last mfa validation String[] items = existingMfaSessionMarker.split(";"); long mfaAuthTime = Long.parseLong(items[0]); MfaMethod mfaMethod = MfaMethod.valueOf(items[1]); log.infof("MFA already valid for this session, skipping mfa check. realm=%s username=%s mfa_method=%s mfa_challenge_timestamp=%s", realm.getName(), username, mfaMethod, mfaAuthTime); context.success(); return; } requestMfaChallenge(context, username, context.getAuthenticationSession()); }
Example 5
Source File: AuthorizationBean.java From keycloak with Apache License 2.0 | 5 votes |
public AuthorizationBean(KeycloakSession session, UserModel user, UriInfo uriInfo) { this.session = session; this.user = user; this.uriInfo = uriInfo; authorization = session.getProvider(AuthorizationProvider.class); List<String> pathParameters = uriInfo.getPathParameters().get("resource_id"); if (pathParameters != null && !pathParameters.isEmpty()) { Resource resource = authorization.getStoreFactory().getResourceStore().findById(pathParameters.get(0), null); if (resource != null && !resource.getOwner().equals(user.getId())) { throw new RuntimeException("User [" + user.getUsername() + "] can not access resource [" + resource.getId() + "]"); } } }
Example 6
Source File: AdminConsole.java From keycloak with Apache License 2.0 | 5 votes |
/** * Permission information * * @param headers * @return */ @Path("whoami") @GET @Produces(MediaType.APPLICATION_JSON) @NoCache public Response whoAmI(final @Context HttpHeaders headers) { RealmManager realmManager = new RealmManager(session); AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers); if (authResult == null) { return Response.status(401).build(); } UserModel user= authResult.getUser(); String displayName; if ((user.getFirstName() != null && !user.getFirstName().trim().equals("")) || (user.getLastName() != null && !user.getLastName().trim().equals(""))) { displayName = user.getFirstName(); if (user.getLastName() != null) { displayName = displayName != null ? displayName + " " + user.getLastName() : user.getLastName(); } } else { displayName = user.getUsername(); } RealmModel masterRealm = getAdminstrationRealm(realmManager); Map<String, Set<String>> realmAccess = new HashMap<String, Set<String>>(); if (masterRealm == null) throw new NotFoundException("No realm found"); boolean createRealm = false; if (realm.equals(masterRealm)) { logger.debug("setting up realm access for a master realm user"); createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM)); addMasterRealmAccess(realm, user, realmAccess); } else { logger.debug("setting up realm access for a realm user"); addRealmAccess(realm, user, realmAccess); } Locale locale = session.getContext().resolveLocale(user); return Response.ok(new WhoAmI(user.getId(), realm.getName(), displayName, createRealm, realmAccess, locale)).build(); }
Example 7
Source File: ThirdPartyMfaAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 4 votes |
@Override public void action(AuthenticationFlowContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); if (formData.containsKey("cancel")) { context.resetFlow(); context.fork(); return; } RealmModel realm = context.getRealm(); UserModel user = context.getUser(); String username = user.getUsername(); log.infof("Request MFA for User. username=%s", username); AuthenticationSessionModel authSession = context.getAuthenticationSession(); MfaMethod mfaMethod = MfaMethod.resolve(authSession.getAuthNote(MFA_METHOD)); if (formData.containsKey(USE_OTP)) { authSession.setAuthNote(MFA_METHOD, MfaMethod.OTP.name()); requestMfaChallenge(context, username, authSession); return; } String mfaChallengeId = authSession.getAuthNote(MFA_CHALLENGE); log.infof("Found challengeId=%s", mfaChallengeId); MfaVerifyRequest mfaRequest = new MfaVerifyRequest(); mfaRequest.setChallengeId(UUID.fromString(mfaChallengeId)); mfaRequest.setChallengeInput(Sanitizers.BLOCKS.sanitize(formData.getFirst("challenge_input"))); MfaVerifyResponse mfaVerifyResponse = mfaClient.verifyAuthChallenge(mfaRequest); if (mfaVerifyResponse.isSuccessful()) { log.infof("MFA authentication successful. realm=%s username=%s mfa_method=%s mfa_challenge_duration=%s", realm.getName(), username, mfaMethod, computeChallengeDuration(authSession)); signalSuccessfulMfaAuthentication(context, authSession, mfaMethod); return; } if (mfaVerifyResponse.isCompleted()) { log.infof("MFA authentication failed. realm=%s username=%s error_code=%s mfa_method=%s mfa_challenge_duration=%s", realm.getName(), user.getUsername(), mfaVerifyResponse.getErrorCode(), mfaMethod, computeChallengeDuration(authSession)); context.getEvent().user(user); String errorMessage = Messages.LOGIN_TIMEOUT; if (MfaVerifyResponse.ERR_TIMEOUT.equals(mfaVerifyResponse.getErrorCode())) { context.getEvent().error(Errors.SESSION_EXPIRED); } else { errorMessage = Messages.INVALID_TOTP; context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); } context.resetFlow(); context.forkWithErrorMessage(new FormMessage(errorMessage)); return; } log.infof("MFA authentication attempt failed. Retrying realm=%s username=%s error_code=%s mfa_method=%s", realm.getName(), user.getUsername(), mfaVerifyResponse.getErrorCode(), mfaMethod); Response response = createChallengeFormResponse(context, false, mfaMethod, mfaVerifyResponse); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, response); }
Example 8
Source File: TokenEndpoint.java From keycloak with Apache License 2.0 | 4 votes |
public Response clientCredentialsGrant() { if (client.isBearerOnly()) { event.error(Errors.INVALID_CLIENT); throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Bearer-only client not allowed to retrieve service account", Response.Status.UNAUTHORIZED); } if (client.isPublicClient()) { event.error(Errors.INVALID_CLIENT); throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Public client not allowed to retrieve service account", Response.Status.UNAUTHORIZED); } if (!client.isServiceAccountsEnabled()) { event.error(Errors.INVALID_CLIENT); throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not enabled to retrieve service account", Response.Status.UNAUTHORIZED); } UserModel clientUser = session.users().getServiceAccount(client); if (clientUser == null || client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) { // May need to handle bootstrap here as well logger.debugf("Service account user for client '%s' not found or default protocol mapper for service account not found. Creating now", client.getClientId()); new ClientManager(new RealmManager(session)).enableServiceAccount(client); clientUser = session.users().getServiceAccount(client); } String clientUsername = clientUser.getUsername(); event.detail(Details.USERNAME, clientUsername); event.user(clientUser); if (!clientUser.isEnabled()) { event.error(Errors.USER_DISABLED); throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "User '" + clientUsername + "' disabled", Response.Status.UNAUTHORIZED); } String scope = getRequestedScopes(); RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false); AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client); authSession.setAuthenticatedUser(clientUser); authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())); authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope); UserSessionModel userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername, clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null); event.session(userSession); AuthenticationManager.setClientScopesInSession(authSession); ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession); // Notes about client details userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId()); userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost()); userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr()); updateUserSessionFromClientAuth(userSession); TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx) .generateAccessToken() .generateRefreshToken(); String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE); if (TokenUtil.isOIDCRequest(scopeParam)) { responseBuilder.generateIDToken().generateAccessTokenHash(); } // TODO : do the same as codeToToken() AccessTokenResponse res = responseBuilder.build(); event.success(); return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build(); }
Example 9
Source File: WebAuthnRegister.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void requiredActionChallenge(RequiredActionContext context) { UserModel userModel = context.getUser(); // Use standard UTF-8 charset to get bytes from string. // Otherwise the platform's default charset is used and it might cause problems later when // decoded on different system. String userId = Base64Url.encode(userModel.getId().getBytes(StandardCharsets.UTF_8)); String username = userModel.getUsername(); Challenge challenge = new DefaultChallenge(); String challengeValue = Base64Url.encode(challenge.getValue()); context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue); // construct parameters for calling WebAuthn API navigator.credential.create() // mandatory WebAuthnPolicy policy = getWebAuthnPolicy(context); List<String> signatureAlgorithmsList = policy.getSignatureAlgorithm(); String signatureAlgorithms = stringifySignatureAlgorithms(signatureAlgorithmsList); String rpEntityName = policy.getRpEntityName(); // optional String rpId = policy.getRpId(); if (rpId == null || rpId.isEmpty()) rpId = context.getUriInfo().getBaseUri().getHost(); String attestationConveyancePreference = policy.getAttestationConveyancePreference(); String authenticatorAttachment = policy.getAuthenticatorAttachment(); String requireResidentKey = policy.getRequireResidentKey(); String userVerificationRequirement = policy.getUserVerificationRequirement(); long createTimeout = policy.getCreateTimeout(); boolean avoidSameAuthenticatorRegister = policy.isAvoidSameAuthenticatorRegister(); String excludeCredentialIds = ""; if (avoidSameAuthenticatorRegister) { List<CredentialModel> webAuthnCredentials = session.userCredentialManager().getStoredCredentialsByType(context.getRealm(), userModel, getCredentialType()); List<String> webAuthnCredentialPubKeyIds = webAuthnCredentials.stream().map(credentialModel -> { WebAuthnCredentialModel credModel = WebAuthnCredentialModel.createFromCredentialModel(credentialModel); return Base64Url.encodeBase64ToBase64Url(credModel.getWebAuthnCredentialData().getCredentialId()); }).collect(Collectors.toList()); excludeCredentialIds = stringifyExcludeCredentialIds(webAuthnCredentialPubKeyIds); } String isSetRetry = context.getHttpRequest().getDecodedFormParameters().getFirst(WebAuthnConstants.IS_SET_RETRY); Response form = context.form() .setAttribute(WebAuthnConstants.CHALLENGE, challengeValue) .setAttribute(WebAuthnConstants.USER_ID, userId) .setAttribute(WebAuthnConstants.USER_NAME, username) .setAttribute(WebAuthnConstants.RP_ENTITY_NAME, rpEntityName) .setAttribute(WebAuthnConstants.SIGNATURE_ALGORITHMS, signatureAlgorithms) .setAttribute(WebAuthnConstants.RP_ID, rpId) .setAttribute(WebAuthnConstants.ATTESTATION_CONVEYANCE_PREFERENCE, attestationConveyancePreference) .setAttribute(WebAuthnConstants.AUTHENTICATOR_ATTACHMENT, authenticatorAttachment) .setAttribute(WebAuthnConstants.REQUIRE_RESIDENT_KEY, requireResidentKey) .setAttribute(WebAuthnConstants.USER_VERIFICATION_REQUIREMENT, userVerificationRequirement) .setAttribute(WebAuthnConstants.CREATE_TIMEOUT, createTimeout) .setAttribute(WebAuthnConstants.EXCLUDE_CREDENTIAL_IDS, excludeCredentialIds) .setAttribute(WebAuthnConstants.IS_SET_RETRY, isSetRetry) .createForm("webauthn-register.ftl"); context.challenge(form); }
Example 10
Source File: PolicyEvaluationResponseBuilder.java From keycloak with Apache License 2.0 | 4 votes |
private static String getUserEmailOrUserName(UserModel user) { return (user.getEmail() != null ? user.getEmail() : user.getUsername()); }
Example 11
Source File: KerberosFederationProvider.java From keycloak with Apache License 2.0 | 4 votes |
public boolean isValid(RealmModel realm, UserModel local) { // KerberosUsernamePasswordAuthenticator.isUserAvailable is an overhead, so avoid it for now String kerberosPrincipal = local.getUsername() + "@" + kerberosConfig.getKerberosRealm(); return kerberosPrincipal.equalsIgnoreCase(local.getFirstAttribute(KERBEROS_PRINCIPAL)); }