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

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#forkWithErrorMessage() . 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: ThirdPartyMfaAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
private void requestMfaChallenge(AuthenticationFlowContext context, String username, AuthenticationSessionModel authSession) {

        MfaChallengeRequest mfaRequest = createMfaChallengeRequest(username, authSession);
        MfaChallengeResponse mfaResponse = mfaClient.requestAuthChallenge(mfaRequest);

        MfaMethod mfaMethod = mfaRequest.getMfaMethod();
        if (mfaResponse.isCompleted()) {
            log.infof("MFA Challenge immediately completed. username=%s challengeId=%s mfa_method=%s mfa_challenge_duration=%s", username, mfaResponse.getChallengeId(), mfaMethod, computeChallengeDuration(authSession));

            signalSuccessfulMfaAuthentication(context, authSession, mfaMethod);
            return;
        }

        if (mfaResponse.isSubmitted()) {
            log.infof("Retrieved challengeId=%s", mfaResponse.getChallengeId());
            authSession.setAuthNote(MFA_CHALLENGE, mfaResponse.getChallengeId().toString());
            authSession.setAuthNote(MFA_CHALLENGE_START, String.valueOf(System.currentTimeMillis()));

            Response response = createChallengeFormResponse(context, true, mfaRequest.getMfaMethod(), mfaResponse);
            context.challenge(response);
            return;
        }

        log.warnf("MFA Challenge request failed. username=%s challengeId=%s mfa_error=%s", username, mfaResponse.getChallengeId(), mfaResponse.getErrorCode());
        context.forkWithErrorMessage(new FormMessage(Messages.FAILED_TO_PROCESS_RESPONSE));
    }
 
Example 2
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 3
Source File: MinPasswordAgeAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    RealmModel realm = context.getRealm();
    UserModel user = context.getUser();
    Map<String, String> config = (context.getAuthenticatorConfig() == null ? Collections.emptyMap() : context.getAuthenticatorConfig().getConfig());

    List<CredentialModel> passwords = context.getSession().userCredentialManager().getStoredCredentialsByType(realm, user, PasswordCredentialModel.TYPE);
    if (!passwords.isEmpty()) {
        CredentialModel passwordCredential = passwords.get(0);

        Instant creationTime = Instant.ofEpochMilli(passwordCredential.getCreatedDate());

        Duration minPasswordAge = Duration.parse(config.getOrDefault(MIN_PASSWORD_AGE_DURATION, "PT15M"));

        if (creationTime.isAfter(Instant.now().minus(minPasswordAge))) {

            log.warnf("Access denied because of min password age. realm=%s username=%s", realm.getName(), user.getUsername());
            context.getEvent().user(user);
            context.getEvent().error(Errors.NOT_ALLOWED);
            context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS));

            return;
        }
    }

    context.success();
}
 
Example 4
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 5
Source File: ThirdPartyMfaAuthenticator.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();

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