Java Code Examples for org.keycloak.authentication.AuthenticationFlowContext#success()

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#success() . 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: 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 2
Source File: NoCookieFlowRedirectAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    HttpRequest httpRequest = context.getHttpRequest();

    // only do redirects for GET requests
    if (HttpMethod.GET.equalsIgnoreCase(httpRequest.getHttpMethod())) {
        KeycloakUriInfo uriInfo = context.getSession().getContext().getUri();
        if (!uriInfo.getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
            Response response = Response.status(302).header(HttpHeaders.LOCATION, context.getRefreshUrl(true)).build();
            context.challenge(response);
            return;
        }
    }

    context.success();
}
 
Example 3
Source File: CookieAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: ConditionalOtpFormAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean tryConcludeBasedOn(OtpDecision state, AuthenticationFlowContext context) {

        switch (state) {

            case SHOW_OTP:
                showOtpForm(context);
                return true;

            case SKIP_OTP:
                context.success();
                return true;

            default:
                return false;
        }
    }
 
Example 5
Source File: RequireRoleAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    AuthenticatorConfigModel configModel = context.getAuthenticatorConfig();

    String roleName = configModel.getConfig().get(RequireRoleAuthenticatorFactory.ROLE);
    RealmModel realm = context.getRealm();
    UserModel user = context.getUser();

    if (userHasRole(realm, user, roleName)) {
        context.success();
        return;
    }

    LOG.debugf("Access denied because of missing role. realm=%s username=%s role=%s", realm.getName(), user.getUsername(), roleName);
    context.getEvent().user(user);
    context.getEvent().error(Errors.NOT_ALLOWED);
    context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS));
}
 
Example 6
Source File: IdpReviewProfileAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
    IdentityProviderModel idpConfig = brokerContext.getIdpConfig();

    if (requiresUpdateProfilePage(context, userCtx, brokerContext)) {

        logger.debugf("Identity provider '%s' requires update profile action for broker user '%s'.", idpConfig.getAlias(), userCtx.getUsername());

        // No formData for first render. The profile is rendered from userCtx
        Response challengeResponse = context.form()
                .setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx)
                .setFormData(null)
                .createUpdateProfilePage();
        context.challenge(challengeResponse);
    } else {
        // Not required to update profile. Marked success
        context.success();
    }
}
 
Example 7
Source File: ThirdPartyMfaAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private void signalSuccessfulMfaAuthentication(AuthenticationFlowContext context, AuthenticationSessionModel authSession, MfaMethod mfaMethod) {

        authSession.removeAuthNote(MFA_CHALLENGE);
        authSession.removeAuthNote(MFA_CHALLENGE_START);

        authSession.setUserSessionNote(MFA_SESSION_MARKER_KEY, System.currentTimeMillis() + ";" + mfaMethod);
        context.success();
    }
 
Example 8
Source File: X509ClientCertificateAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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 9
Source File: UsernameOnlyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    String username = context.getHttpRequest().getDecodedFormParameters().getFirst("username");
    UserModel user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    if (user == null) {
        context.failure(AuthenticationFlowError.UNKNOWN_USER);
        return;
    }
    context.setUser(user);
    context.success();
}
 
Example 10
Source File: KeycloakSmsAuthenticator.java    From keycloak-sms-authenticator with Eclipse Public License 2.0 5 votes vote down vote up
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 11
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    if (formData.containsKey("cancel")) {
        context.cancelLogin();
        return;
    }
    if (!validateUsernameForm(context, formData)) {
        return;
    }
    context.success();
}
 
Example 12
Source File: AccessPolicyAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: LoginNotifyEmailAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    UserModel user = context.getUser();

    long currentLoginTime = System.currentTimeMillis();
    long lastLoginTime = detectLastLoginTimeForUser(user, currentLoginTime);

    try {
        if (user.getEmail() != null) {
            String timeSinceLastEmail = getConfigSettingOrDefault(context, TIME_SINCE_LAST_LOGIN, null);
            if (timeSinceLastEmail != null) {
                Duration duration = Duration.parse(timeSinceLastEmail);
                Instant lastLogin = Instant.ofEpochMilli(lastLoginTime);
                Instant currentLogin = Instant.ofEpochMilli(currentLoginTime);
                if (lastLogin.plus(duration).isBefore(currentLogin)) {
                    log.infof("Sending login notification email after longer absence. userId=%s", user.getUsername());
                    sendLoginNotificationEmail(context, user);
                }
            }
        }
    } catch (Exception ex) {
        log.warnf("Could not send login notification email after longer absence. userId=%s", user.getId(), ex);
    } finally {
        updateLastLoginTimeForUser(user, currentLoginTime);
        context.success();
    }
}
 
Example 14
Source File: IdpAutoLinkAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    KeycloakSession session = context.getSession();
    RealmModel realm = context.getRealm();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    UserModel existingUser = getExistingUser(session, realm, authSession);

    logger.debugf("User '%s' is set to authentication context when link with identity provider '%s' . Identity provider username is '%s' ", existingUser.getUsername(),
            brokerContext.getIdpConfig().getAlias(), brokerContext.getUsername());

    context.setUser(existingUser);
    context.success();
}
 
Example 15
Source File: ResetPassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    if (context.getExecution().isRequired() ||
            (context.getExecution().isConditional() &&
                    configuredFor(context))) {
        context.getAuthenticationSession().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    }
    context.success();
}
 
Example 16
Source File: UsernamePasswordForm.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    if (formData.containsKey("cancel")) {
        context.cancelLogin();
        return;
    }
    if (!validateForm(context, formData)) {
        return;
    }
    context.success();
}
 
Example 17
Source File: AuthzPolicyAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    RealmModel realm = context.getRealm();
    ClientModel client = context.getAuthenticationSession().getClient();

    AuthorizationProvider authzProvider = session.getProvider(AuthorizationProvider.class);
    PolicyStore policyStore = authzProvider.getStoreFactory().getPolicyStore();

    AuthenticatorConfigModel configModel = context.getAuthenticatorConfig();
    Map<String, String> config = configModel.getConfig();

    String clientPolicyName = config.get(CLIENTS_POLICY);
    String rolePolicyName = config.get(ROLES_POLICY);

    String realmManagementClientId = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID).getId();
    Policy clientPolicy = policyStore.findByName(clientPolicyName, realmManagementClientId);

    List<String> clients = parseJson(clientPolicy.getConfig().get("clients"), List.class);
    if (!clients.contains(client.getId())) {
        // The current client is not contained in the client policy -> skip the authenticator
        context.success();
        return;
    }

    Policy rolePolicy = policyStore.findByName(rolePolicyName, realmManagementClientId);
    List<Map<String, Object>> roles = parseJson(rolePolicy.getConfig().get("roles"), List.class);
    List<RoleModel> requiredRoles = roles.stream()
            .map(r -> (String) r.get("id"))
            .map(realm::getRoleById)
            .collect(Collectors.toList());

    UserModel user = context.getUser();
    boolean accessAllowed = requiredRoles.stream().anyMatch(user::hasRole);

    if (accessAllowed) {
        // the user has the required roles -> let the authentication succeed
        context.success();
        return;
    }

    // the user does not have the required roles -> deny the authentication

    context.getEvent().user(user);
    context.getEvent().error(Errors.NOT_ALLOWED);
    context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS));
}
 
Example 18
Source File: WebAuthn4jAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 4 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

    // receive error from navigator.credentials.get()
    String error = params.getFirst(WebAuthnConstants.ERROR);
    if (error != null && !error.isEmpty()) {
        throw new AuthenticationFlowException("exception raised from navigator.credentials.get() : " + error, AuthenticationFlowError.INVALID_USER);
    }

    String baseUrl = UriUtils.getOrigin(context.getUriInfo().getBaseUri());
    String rpId = context.getUriInfo().getBaseUri().getHost();

    Origin origin = new Origin(baseUrl);
    Challenge challenge = new DefaultChallenge(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE));
    ServerProperty server = new ServerProperty(origin, rpId, challenge, null);

    byte[] credentialId = Base64Url.decode(params.getFirst(WebAuthnConstants.CREDENTIAL_ID));
    byte[] clientDataJSON = Base64Url.decode(params.getFirst(WebAuthnConstants.CLIENT_DATA_JSON));
    byte[] authenticatorData = Base64Url.decode(params.getFirst(WebAuthnConstants.AUTHENTICATOR_DATA));
    byte[] signature = Base64Url.decode(params.getFirst(WebAuthnConstants.SIGNATURE));

    String userId = params.getFirst(WebAuthnConstants.USER_HANDLE);
    boolean isUVFlagChecked = true;
    logger.debugv("userId = {0}", userId);

    if (userId == null || userId.isEmpty()) {
        // in 2 Factor with Resident Key not supported Authenticator Scenario
        userId = context.getUser().getId();
        isUVFlagChecked = false;
    } else {
        if (context.getUser() != null) {
            // in 2 Factor with Resident Key supported Authenticator Scenario
            String firstAuthenticatedUserId = context.getUser().getId();
            logger.debugv("firstAuthenticatedUserId = {0}", firstAuthenticatedUserId);
            if (firstAuthenticatedUserId != null && !firstAuthenticatedUserId.equals(userId)) {
                throw new AuthenticationFlowException("First authenticated user is not the one authenticated by 2nd factor authenticator", AuthenticationFlowError.USER_CONFLICT);
            }
        } else {
            // in Passwordless with Resident Key supported Authenticator Scenario
            // NOP
        }
    }
    UserModel user = session.users().getUserById(userId, context.getRealm());
    WebAuthnAuthenticationContext authenticationContext = new WebAuthnAuthenticationContext(
            credentialId,
            clientDataJSON,
            authenticatorData,
            signature,
            server,
            isUVFlagChecked
    );

    WebAuthnCredentialModel cred = new WebAuthnCredentialModel();
    cred.setAuthenticationContext(authenticationContext);

    boolean result = false;
    try {
        result = session.userCredentialManager().isValid(context.getRealm(), user, cred);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationFlowException("unknown user authenticated by the authenticator", AuthenticationFlowError.UNKNOWN_USER);
    }
    if (result) {
        context.setUser(user);
        context.success();
    } else {
        context.cancelLogin();
    }
}
 
Example 19
Source File: ResetOTP.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    context.getAuthenticationSession().addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP);
    context.success();
}
 
Example 20
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void userSuccessAction(AuthenticationFlowContext context, UserModel user) {
    context.getAuthenticationSession().setAuthenticatedUser(user);
    context.success();
}