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

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#cancelLogin() . 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: RequireGroupAuthenticator.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 groupPath = configModel.getConfig().get(RequireGroupAuthenticatorFactory.GROUP);
    RealmModel realm = context.getRealm();
    UserModel user = context.getUser();

    if (!isMemberOfGroup(realm, user, groupPath)) {

        LOG.debugf("Access denied because of missing group membership. realm=%s username=%s groupPath=%s", realm.getName(), user.getUsername(), groupPath);
        context.cancelLogin();
        return;
    }

    context.success();
}
 
Example 3
Source File: TenantSelectorAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String tenant = formData.getFirst("tenant");
    String group = formData.getFirst("group");

    LOG.infof("Retrieved tenant=%s group=%s", tenant, group);

    if (group == null || tenant == null || group.trim().isEmpty() || tenant.trim().isEmpty()) {

        context.cancelLogin();

        // reauthenticate...
        authenticate(context);
        return;
    }

    // Add selected information to authentication session
    context.getAuthenticationSession().setUserSessionNote("tenant", tenant);
    context.getAuthenticationSession().setUserSessionNote("group", group);

    context.success();
}
 
Example 4
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 5
Source File: PasswordAuthenticatorForm.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();
        context.resetFlow();
        return;
    }
    if (!validatePasswordForm(context, formData)) {
        return;
    }

    context.success();
}
 
Example 6
Source File: SimpleAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    int expectedSum = Integer.parseInt(context.getAuthenticationSession().getAuthNote(EXPECTED_SUM));
    int givenSum = Integer.parseInt(formData.getFirst("givenSum"));

    LOG.infof("Retrieved givenSum=%s expectedSum=%s", givenSum, expectedSum);

    context.getAuthenticationSession().removeAuthNote(EXPECTED_SUM);

    if (givenSum != expectedSum) {

        context.cancelLogin();

        // reauthenticate...
        authenticate(context);
        return;
    }

    context.success();
}
 
Example 7
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 8
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

    context.getEvent().detail(Details.CREDENTIAL_TYPE, getCredentialType());

    // receive error from navigator.credentials.get()
    String errorMsgFromWebAuthnApi = params.getFirst(WebAuthnConstants.ERROR);
    if (errorMsgFromWebAuthnApi != null && !errorMsgFromWebAuthnApi.isEmpty()) {
        setErrorResponse(context, WEBAUTHN_ERROR_API_GET, errorMsgFromWebAuthnApi);
        return;
    }

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

    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));

    final String userHandle = params.getFirst(WebAuthnConstants.USER_HANDLE);
    final String userId;
    // existing User Handle means that the authenticator used Resident Key supported public key credential
    if (userHandle == null || userHandle.isEmpty()) {
        // Resident Key not supported public key credential was used
        // so rely on the user that has already been authenticated
        userId = context.getUser().getId();
    } else {
        // decode using the same charset as it has been encoded (see: WebAuthnRegister.java)
        userId = new String(Base64Url.decode(userHandle), StandardCharsets.UTF_8);
        if (context.getUser() != null) {
            // Resident Key supported public key credential was used,
            // so need to confirm whether the already authenticated user is equals to one authenticated by the webauthn authenticator
            String firstAuthenticatedUserId = context.getUser().getId();
            if (firstAuthenticatedUserId != null && !firstAuthenticatedUserId.equals(userId)) {
                context.getEvent()
                        .detail("first_authenticated_user_id", firstAuthenticatedUserId)
                        .detail("web_authn_authenticator_authenticated_user_id", userId);
                setErrorResponse(context, WEBAUTHN_ERROR_DIFFERENT_USER, null);
                return;
            }
        } else {
            // Resident Key supported public key credential was used,
            // and the user has not yet been identified
            // so rely on the user authenticated by the webauthn authenticator
            // NOP
        }
    }

    boolean isUVFlagChecked = false;
    String userVerificationRequirement = getWebAuthnPolicy(context).getUserVerificationRequirement();
    if (WebAuthnConstants.OPTION_REQUIRED.equals(userVerificationRequirement)) isUVFlagChecked = true;

    UserModel user = session.users().getUserById(userId, context.getRealm());

    AuthenticationRequest authenticationRequest = new AuthenticationRequest(
            credentialId,
            authenticatorData,
            clientDataJSON,
            signature
            );

    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            server,
            null, // here authenticator cannot be fetched, set it afterwards in WebAuthnCredentialProvider.isValid()
            isUVFlagChecked
            );

    WebAuthnCredentialModelInput cred = new WebAuthnCredentialModelInput(getCredentialType());

    cred.setAuthenticationRequest(authenticationRequest);
    cred.setAuthenticationParameters(authenticationParameters);

    boolean result = false;
    try {
        result = session.userCredentialManager().isValid(context.getRealm(), user, cred);
    } catch (WebAuthnException wae) {
        setErrorResponse(context, WEBAUTHN_ERROR_AUTH_VERIFICATION, wae.getMessage());
        return;
    }
    String encodedCredentialID = Base64Url.encode(credentialId);
    if (result) {
        String isUVChecked = Boolean.toString(isUVFlagChecked);
        logger.debugv("WebAuthn Authentication successed. isUserVerificationChecked = {0}, PublicKeyCredentialID = {1}", isUVChecked, encodedCredentialID);
        context.setUser(user);
        context.getEvent()
            .detail("web_authn_authenticator_user_verification_checked", isUVChecked)
            .detail("public_key_credential_id", encodedCredentialID);
        context.success();
    } else {
        context.getEvent()
            .detail("web_authn_authenticated_user_id", userId)
            .detail("public_key_credential_id", encodedCredentialID);
        setErrorResponse(context, WEBAUTHN_ERROR_USER_NOT_FOUND, null);
        context.cancelLogin();
    }
}
 
Example 9
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();
}