Java Code Examples for org.keycloak.authentication.AuthenticationFlowContext#attempted()
The following examples show how to use
org.keycloak.authentication.AuthenticationFlowContext#attempted() .
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: DynamicIdpRedirectAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 6 votes |
@Override public void authenticate(AuthenticationFlowContext context) { UserModel user = context.getUser(); if (user == null) { context.attempted(); return; } String targetIdp = determineTargetIdp(user, context); if (targetIdp != null) { redirect(context, targetIdp); return; } boolean fallbackToAuthFlow = getConfigValueOrDefault(context.getAuthenticatorConfig(), FALLBACK_TO_AUTHFLOW_CONFIG_PROPERTY, "true", Boolean::parseBoolean); if (fallbackToAuthFlow) { context.attempted(); return; } context.getEvent().error(Errors.UNKNOWN_IDENTITY_PROVIDER); context.failure(AuthenticationFlowError.IDENTITY_PROVIDER_NOT_FOUND); context.cancelLogin(); context.resetFlow(); }
Example 2
Source File: DynamicIdpRedirectAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 6 votes |
protected void redirect(AuthenticationFlowContext context, String providerId) { IdentityProviderModel identityProviderModel = selectIdp(context, providerId); if (identityProviderModel == null || !identityProviderModel.isEnabled()) { log.warnf("Provider not found or not enabled for realm %s", providerId); context.attempted(); return; } String accessCode = new ClientSessionCode<>(context.getSession(), context.getRealm(), context.getAuthenticationSession()).getOrGenerateCode(); String clientId = context.getAuthenticationSession().getClient().getClientId(); String tabId = context.getAuthenticationSession().getTabId(); URI location = Urls.identityProviderAuthnRequest(context.getUriInfo().getBaseUri(), providerId, context.getRealm().getName(), accessCode, clientId, tabId); if (context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY) != null) { location = UriBuilder.fromUri(location).queryParam(OAuth2Constants.DISPLAY, context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY)).build(); } log.debugf("Redirecting to %s", providerId); Response response = Response.seeOther(location).build(); context.forceChallenge(response); }
Example 3
Source File: ExpectedParamAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void authenticate(AuthenticationFlowContext context) { String paramValue = context.getAuthenticationSession().getClientNote(AuthorizationEndpoint.LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX + "foo"); String expectedValue = context.getAuthenticatorConfig().getConfig().get(EXPECTED_VALUE); logger.info("Value: " + paramValue + ", expectedValue: " + expectedValue); if (paramValue != null && paramValue.equals(expectedValue)) { String loggedUser = context.getAuthenticatorConfig().getConfig().get(LOGGED_USER); if (loggedUser == null) { logger.info("Successfully authenticated, but don't set any authenticated user"); } else { UserModel user = context.getSession().users().getUserByUsername(loggedUser, context.getRealm()); logger.info("Successfully authenticated as user " + user.getUsername()); context.setUser(user); } context.success(); } else { context.attempted(); } }
Example 4
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 5
Source File: CookieAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void authenticate(AuthenticationFlowContext context) { AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(context.getSession(), context.getRealm(), true); if (authResult == null) { context.attempted(); } else { AuthenticationSessionModel clientSession = context.getAuthenticationSession(); LoginProtocol protocol = context.getSession().getProvider(LoginProtocol.class, clientSession.getProtocol()); // Cookie re-authentication is skipped if re-authentication is required if (protocol.requireReauthentication(authResult.getSession(), clientSession)) { context.attempted(); } else { context.getSession().setAttribute(AuthenticationManager.SSO_AUTH, "true"); context.setUser(authResult.getUser()); context.attachUserSession(authResult.getSession()); context.success(); } } }
Example 6
Source File: IdentityProviderAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void authenticate(AuthenticationFlowContext context) { if (context.getUriInfo().getQueryParameters().containsKey(AdapterConstants.KC_IDP_HINT)) { String providerId = context.getUriInfo().getQueryParameters().getFirst(AdapterConstants.KC_IDP_HINT); if (providerId == null || providerId.equals("")) { LOG.tracef("Skipping: kc_idp_hint query parameter is empty"); context.attempted(); } else { LOG.tracef("Redirecting: %s set to %s", AdapterConstants.KC_IDP_HINT, providerId); redirect(context, providerId); } } else if (context.getAuthenticatorConfig() != null && context.getAuthenticatorConfig().getConfig().containsKey(IdentityProviderAuthenticatorFactory.DEFAULT_PROVIDER)) { String defaultProvider = context.getAuthenticatorConfig().getConfig().get(IdentityProviderAuthenticatorFactory.DEFAULT_PROVIDER); LOG.tracef("Redirecting: default provider set to %s", defaultProvider); redirect(context, defaultProvider); } else { LOG.tracef("No default provider set or %s query parameter provided", AdapterConstants.KC_IDP_HINT); context.attempted(); } }
Example 7
Source File: IdpConfirmLinkAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
@Override protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) { AuthenticationSessionModel authSession = context.getAuthenticationSession(); String existingUserInfo = authSession.getAuthNote(EXISTING_USER_INFO); if (existingUserInfo == null) { ServicesLogger.LOGGER.noDuplicationDetected(); context.attempted(); return; } ExistingUserInfo duplicationInfo = ExistingUserInfo.deserialize(existingUserInfo); Response challenge = context.form() .setStatus(Response.Status.OK) .setAttribute(LoginFormsProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext) .setError(Messages.FEDERATED_IDENTITY_CONFIRM_LINK_MESSAGE, duplicationInfo.getDuplicateAttributeName(), duplicationInfo.getDuplicateAttributeValue()) .createIdpLinkConfirmLinkPage(); context.challenge(challenge); }
Example 8
Source File: AccessPolicyAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 5 votes |
@Override public void authenticate(AuthenticationFlowContext context) { AuthenticatorConfigModel configModel = context.getAuthenticatorConfig(); if (configModel == null) { context.attempted(); return; } String accessPolicyJson = configModel.getConfig().get(AccessPolicyAuthenticatorFactory.ACCESS_POLICY); if (accessPolicyJson == null) { context.attempted(); return; } AccessPolicy accessPolicy = accessPolicyParser.parse(accessPolicyJson); RealmModel realm = context.getRealm(); ClientModel client = context.getAuthenticationSession().getClient(); UserModel user = context.getUser(); if (!accessPolicy.hasAccess(realm, user, client)) { log.debugf("Access denied because of access policy. realm=%s client=%s username=%s", realm.getName(), client.getClientId(), user.getUsername()); context.getEvent().user(user); context.getEvent().error(Errors.NOT_ALLOWED); context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS)); return; } context.success(); }
Example 9
Source File: KeycloakSmsAuthenticator.java From keycloak-sms-authenticator with Eclipse Public License 2.0 | 5 votes |
public void action(AuthenticationFlowContext context) { logger.debug("action called ... context = " + context); CODE_STATUS status = validateCode(context); Response challenge = null; switch (status) { case EXPIRED: challenge = context.form() .setError("code is expired") .createForm("sms-validation.ftl"); context.failureChallenge(AuthenticationFlowError.EXPIRED_CODE, challenge); break; case INVALID: if(context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.OPTIONAL || context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.ALTERNATIVE) { logger.debug("Calling context.attempted()"); context.attempted(); } else if(context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.REQUIRED) { challenge = context.form() .setError("badCode") .createForm("sms-validation.ftl"); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge); } else { // Something strange happened logger.warn("Undefined execution ..."); } break; case VALID: context.success(); break; } }
Example 10
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 11
Source File: X509ClientCertificateAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void action(AuthenticationFlowContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); if (formData.containsKey("cancel")) { context.clearUser(); context.attempted(); return; } if (context.getUser() != null) { recordX509CertificateAuditDataViaContextEvent(context); context.success(); return; } context.attempted(); }
Example 12
Source File: IdentityProviderAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
private void redirect(AuthenticationFlowContext context, String providerId) { List<IdentityProviderModel> identityProviders = context.getRealm().getIdentityProviders(); for (IdentityProviderModel identityProvider : identityProviders) { if (identityProvider.isEnabled() && providerId.equals(identityProvider.getAlias())) { String accessCode = new ClientSessionCode<>(context.getSession(), context.getRealm(), context.getAuthenticationSession()).getOrGenerateCode(); String clientId = context.getAuthenticationSession().getClient().getClientId(); String tabId = context.getAuthenticationSession().getTabId(); URI location = Urls.identityProviderAuthnRequest(context.getUriInfo().getBaseUri(), providerId, context.getRealm().getName(), accessCode, clientId, tabId); if (context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY) != null) { location = UriBuilder.fromUri(location).queryParam(OAuth2Constants.DISPLAY, context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY)).build(); } Response response = Response.seeOther(location) .build(); // will forward the request to the IDP with prompt=none if the IDP accepts forwards with prompt=none. if ("none".equals(context.getAuthenticationSession().getClientNote(OIDCLoginProtocol.PROMPT_PARAM)) && Boolean.valueOf(identityProvider.getConfig().get(ACCEPTS_PROMPT_NONE))) { context.getAuthenticationSession().setAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN, "true"); } LOG.debugf("Redirecting to %s", providerId); context.forceChallenge(response); return; } } LOG.warnf("Provider not found or not enabled for realm %s", providerId); context.attempted(); }
Example 13
Source File: SessionPropagationAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 4 votes |
@Override public void authenticate(AuthenticationFlowContext context) { MultivaluedMap<String, String> queryParameters = context.getHttpRequest().getUri().getQueryParameters(); String encryptedSessionReferenceData = queryParameters.getFirst("ksr"); if (encryptedSessionReferenceData == null) { log.infof("Reject session propagation. Reason: Missing sessionReferenceData."); context.attempted(); return; } String encryptedSessionReferenceSalt = queryParameters.getFirst("ksrs"); if (encryptedSessionReferenceSalt == null) { log.infof("Reject session propagation. Reason: Missing encryptedSessionReferenceSalt."); context.attempted(); return; } log.infof("Attempting user session propagation..."); // TODO use encryption key from env variable to avoid exposing this via the admin-console String sharedEncryptionKey = getConfigProperty(context, ENCRYPTION_KEY, "changeme"); String sessionReferenceData; try { sessionReferenceData = CryptoUtil.decrypt(encryptedSessionReferenceData, encryptionKeyFrom(sharedEncryptionKey, encryptedSessionReferenceSalt)); } catch (Exception ex) { context.failure(AuthenticationFlowError.INVALID_CREDENTIALS); log.infof("Reject session propagation. Reason: bad encryptedSessionReferenceData."); return; } String[] items = sessionReferenceData != null ? sessionReferenceData.split(";") : new String[0]; if (items.length != 2) { context.failure(AuthenticationFlowError.INVALID_CREDENTIALS); log.infof("Reject session propagation. Reason: bad sessionReferenceData."); return; } long timestamp = Long.parseLong(items[0]); int sessionReferenceMaxAgeSeconds = Integer.parseInt(getConfigProperty(context, SESSION_REFERENCE_MAX_AGE_SECONDS, "30")); boolean sessionReferenceToOld = Instant.now().isAfter(Instant.ofEpochMilli(timestamp).plus(sessionReferenceMaxAgeSeconds, ChronoUnit.SECONDS)); if (sessionReferenceToOld) { context.failure(AuthenticationFlowError.INVALID_CLIENT_SESSION); log.infof("Reject session propagation. Reason: session reference to old."); return; } String sessionHandle = items[1]; KeycloakSessionInfo keycloakSessionInfo = resolveKeycloakSessionId(sessionHandle, sharedEncryptionKey, encryptedSessionReferenceSalt, getConfigProperty(context, SESSION_VALIDATION_SERVICE_URL, null)); if (keycloakSessionInfo == null) { context.failure(AuthenticationFlowError.INVALID_CLIENT_SESSION); log.infof("Reject session propagation. Reason: Remote session not found."); return; } String keycloakSessionId = keycloakSessionInfo.getKeycloakSessionId(); RealmModel realm = context.getRealm(); UserSessionModel userSession = session.sessions().getUserSession(realm, keycloakSessionId); if (userSession == null) { context.failure(AuthenticationFlowError.INVALID_CLIENT_SESSION); log.infof("Reject session propagation. Reason: keycloak session not found."); return; } if (!keycloakSessionInfo.getUsername().equals(userSession.getUser().getUsername())) { context.failure(AuthenticationFlowError.INVALID_CLIENT_SESSION); log.infof("Reject session propagation. Reason: username mismatch."); return; } // TODO check if session propagation is allowed for client... log.infof("Successful user session propagation."); context.getAuthenticationSession().setAuthenticatedUser(userSession.getUser()); context.success(); }
Example 14
Source File: AttemptedAuthenticator.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void authenticate(AuthenticationFlowContext context) { context.attempted(); }
Example 15
Source File: SpnegoAuthenticator.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void action(AuthenticationFlowContext context) { context.attempted(); return; }
Example 16
Source File: IdpCreateUserIfUniqueAuthenticator.java From keycloak with Apache License 2.0 | 4 votes |
@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(); } } }