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

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#failure() . 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 vote down vote up
@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: ScriptBasedAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void tryInvoke(String functionName, AuthenticationFlowContext context) {

        if (!hasAuthenticatorConfig(context)) {
            // this is an empty not yet configured script authenticator
            // we mark this execution as success to not lock out users due to incompletely configured authenticators.
            context.success();
            return;
        }

        InvocableScriptAdapter invocableScriptAdapter = getInvocableScriptAdapter(context);

        if (!invocableScriptAdapter.isDefined(functionName)) {
            return;
        }

        try {
            //should context be wrapped in a read-only wrapper?
            invocableScriptAdapter.invokeFunction(functionName, context);
        } catch (ScriptExecutionException e) {
            LOGGER.error(e);
            context.failure(AuthenticationFlowError.INTERNAL_ERROR);
        }
    }
 
Example 3
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 4
Source File: PassThroughAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    UserModel user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    if (user == null) {
        context.failure(AuthenticationFlowError.UNKNOWN_USER);
        return;
    }
    context.setUser(user);
    context.success();
}
 
Example 5
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void userDisabledAction(AuthenticationFlowContext context, RealmModel realm, UserModel user, String eventError) {
    context.getEvent().user(user);
    context.getEvent().error(eventError);
    context.failure(AuthenticationFlowError.INVALID_USER, Response.status(Response.Status.UNAUTHORIZED)
            .header(HttpHeaders.WWW_AUTHENTICATE, BASIC_PREFIX + "realm=\"" + realm.getName() + "\"")
            .build());
}
 
Example 6
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void notValidCredentialsAction(final AuthenticationFlowContext context, final RealmModel realm, final UserModel user) {
    context.getEvent().user(user);
    context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
    context.failure(AuthenticationFlowError.INVALID_USER, Response.status(Response.Status.UNAUTHORIZED)
            .header(HttpHeaders.WWW_AUTHENTICATE, BASIC_PREFIX + "realm=\"" + realm.getName() + "\"")
            .build());
}
 
Example 7
Source File: ValidatePassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: SessionPropagationAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
@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 9
Source File: SetUserAttributeAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
    context.failure(AuthenticationFlowError.INTERNAL_ERROR);
}
 
Example 10
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void setErrorResponse(AuthenticationFlowContext context, final String errorCase, final String errorMessage) {
    Response errorResponse = null;
    switch (errorCase) {
    case WEBAUTHN_ERROR_REGISTRATION:
        logger.warn(errorCase);
        context.getEvent()
            .detail(ERR_LABEL, errorCase)
            .error(Errors.INVALID_USER_CREDENTIALS);
        errorResponse = createErrorResponse(context, errorCase);
        context.failure(AuthenticationFlowError.INVALID_CREDENTIALS, errorResponse);
        break;
    case WEBAUTHN_ERROR_API_GET:
        logger.warnv("error returned from navigator.credentials.get(). {0}", errorMessage);
        context.getEvent()
            .detail(ERR_LABEL, errorCase)
            .detail(ERR_DETAIL_LABEL, errorMessage)
            .error(Errors.NOT_ALLOWED);
        errorResponse = createErrorResponse(context, errorCase);
        context.failure(AuthenticationFlowError.INVALID_USER, errorResponse);
        break;
    case WEBAUTHN_ERROR_DIFFERENT_USER:
        logger.warn(errorCase);
        context.getEvent()
            .detail(ERR_LABEL, errorCase)
            .error(Errors.DIFFERENT_USER_AUTHENTICATED);
        errorResponse = createErrorResponse(context, errorCase);
        context.failure(AuthenticationFlowError.USER_CONFLICT, errorResponse);
        break;
    case WEBAUTHN_ERROR_AUTH_VERIFICATION:
        logger.warnv("WebAuthn API .get() response validation failure. {0}", errorMessage);
        context.getEvent()
            .detail(ERR_LABEL, errorCase)
            .detail(ERR_DETAIL_LABEL, errorMessage)
            .error(Errors.INVALID_USER_CREDENTIALS);
        errorResponse = createErrorResponse(context, errorCase);
        context.failure(AuthenticationFlowError.INVALID_USER, errorResponse);
        break;
    case WEBAUTHN_ERROR_USER_NOT_FOUND:
        logger.warn(errorCase);
        context.getEvent()
                .detail(ERR_LABEL, errorCase)
                .error(Errors.USER_NOT_FOUND);
        errorResponse = createErrorResponse(context, errorCase);
        context.failure(AuthenticationFlowError.UNKNOWN_USER, errorResponse);
        break;
    default:
            // NOP
    }
}
 
Example 11
Source File: IdpEmailVerificationAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void sendVerifyEmail(KeycloakSession session, AuthenticationFlowContext context, UserModel existingUser, BrokeredIdentityContext brokerContext) throws UriBuilderException, IllegalArgumentException {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(IdpVerifyAccountLinkActionToken.TOKEN_TYPE);
    int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;

    EventBuilder event = context.getEvent().clone().event(EventType.SEND_IDENTITY_PROVIDER_LINK)
            .user(existingUser)
            .detail(Details.USERNAME, existingUser.getUsername())
            .detail(Details.EMAIL, existingUser.getEmail())
            .detail(Details.CODE_ID, authSession.getParentSession().getId())
            .removeDetail(Details.AUTH_METHOD)
            .removeDetail(Details.AUTH_TYPE);

    String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
    IdpVerifyAccountLinkActionToken token = new IdpVerifyAccountLinkActionToken(
      existingUser.getId(), absoluteExpirationInSecs, authSessionEncodedId,
      brokerContext.getUsername(), brokerContext.getIdpConfig().getAlias(), authSession.getClient().getClientId()
    );
    UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo),
            authSession.getClient().getClientId(), authSession.getTabId());
    String link = builder
            .queryParam(Constants.EXECUTION, context.getExecution().getId())
            .build(realm.getName()).toString();
    long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);

    try {
        context.getSession().getProvider(EmailTemplateProvider.class)
                .setRealm(realm)
                .setAuthenticationSession(authSession)
                .setUser(existingUser)
                .setAttribute(EmailTemplateProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext)
                .sendConfirmIdentityBrokerLink(link, expirationInMinutes);

        event.success();
    } catch (EmailException e) {
        event.error(Errors.EMAIL_SEND_FAILED);

        ServicesLogger.LOGGER.confirmBrokerEmailFailed(e);
        Response challenge = context.form()
                .setError(Messages.EMAIL_SENT_ERROR)
                .createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
        context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
        return;
    }

    showEmailSentPage(context, brokerContext);
}