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

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#getAuthenticatorConfig() . 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: IdpReviewProfileAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean requiresUpdateProfilePage(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
    String enforceUpdateProfile = context.getAuthenticationSession().getAuthNote(ENFORCE_UPDATE_PROFILE);
    if (Boolean.parseBoolean(enforceUpdateProfile)) {
        return true;
    }

    String updateProfileFirstLogin;
    AuthenticatorConfigModel authenticatorConfig = context.getAuthenticatorConfig();
    if (authenticatorConfig == null || !authenticatorConfig.getConfig().containsKey(IdpReviewProfileAuthenticatorFactory.UPDATE_PROFILE_ON_FIRST_LOGIN)) {
        updateProfileFirstLogin = IdentityProviderRepresentation.UPFLM_MISSING;
    } else {
        updateProfileFirstLogin = authenticatorConfig.getConfig().get(IdpReviewProfileAuthenticatorFactory.UPDATE_PROFILE_ON_FIRST_LOGIN);
    }

    RealmModel realm = context.getRealm();
    return IdentityProviderRepresentation.UPFLM_ON.equals(updateProfileFirstLogin)
            || (IdentityProviderRepresentation.UPFLM_MISSING.equals(updateProfileFirstLogin) && !Validation.validateUserMandatoryFields(realm, userCtx));
}
 
Example 2
Source File: ConditionalOnScopePresentAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {

    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (authConfig == null) {
        return false;
    }

    Map<String, String> config = authConfig.getConfig();
    String requiredScopeName = config != null ? config.get(CLIENT_SCOPE_NAME) : null;

    ClientModel client = context.getSession().getContext().getClient();
    Map<String, ClientScopeModel> clientScopes = client.getClientScopes(true, true);

    return clientScopes != null && clientScopes.containsKey(requiredScopeName);
}
 
Example 3
Source File: IdentityProviderAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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 4
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 5
Source File: ConditionalRoleAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    RealmModel realm = context.getRealm();
    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (user != null && authConfig!=null && authConfig.getConfig()!=null) {
        String requiredRole = authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONDITIONAL_USER_ROLE);
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, requiredRole);
        if (role == null) {
            logger.errorv("Invalid role name submitted: {0}", requiredRole);
            return false;
        }
        return user.hasRole(role);
    }
    return false;
}
 
Example 6
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 7
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
	context.getEvent().detail(Details.AUTH_METHOD, "auth_method");
	if (logger.isInfoEnabled()) {
		logger.info(
				"validateRecaptcha(AuthenticationFlowContext, boolean, String, String) - Before the validation");
	}

	AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
	LoginFormsProvider form = context.form();
	String userLanguageTag = context.getSession().getContext().resolveLocale(context.getUser()).toLanguageTag();

	if (captchaConfig == null || captchaConfig.getConfig() == null
			|| captchaConfig.getConfig().get(SITE_KEY) == null
			|| captchaConfig.getConfig().get(SITE_SECRET) == null) {
		form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED));
		return;
	}
	siteKey = captchaConfig.getConfig().get(SITE_KEY);
	form.setAttribute("recaptchaRequired", true);
	form.setAttribute("recaptchaSiteKey", siteKey);
	form.addScript("https://www.google.com/recaptcha/api.js?hl=" + userLanguageTag);

	super.authenticate(context);
}
 
Example 8
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private String getConfigProperty(AuthenticationFlowContext context, String configProperty, String defaultValue) {

        AuthenticatorConfigModel authenticatorConfig = context.getAuthenticatorConfig();
        if (authenticatorConfig == null) {
            return defaultValue;
        }

        Map<String, String> config = authenticatorConfig.getConfig();
        if (config == null) {
            return defaultValue;
        }

        return config.get(configProperty);
    }
 
Example 9
Source File: SecretQuestionAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setCookie(AuthenticationFlowContext context) {
    AuthenticatorConfigModel config = context.getAuthenticatorConfig();
    int maxCookieAge = 60 * 60 * 24 * 30; // 30 days
    if (config != null) {
        maxCookieAge = Integer.valueOf(config.getConfig().get("cookie.max.age"));

    }
    URI uri = context.getUriInfo().getBaseUriBuilder().path("realms").path(context.getRealm().getName()).build();
    addCookie(context, "SECRET_QUESTION_ANSWERED", "true",
            uri.getRawPath(),
            null, null,
            maxCookieAge,
            false, true);
}
 
Example 10
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 5 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
	if (logger.isDebugEnabled()) {
		logger.debug("action(AuthenticationFlowContext) - start");
	}
	MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
	List<FormMessage> errors = new ArrayList<>();
	boolean success = false;
	context.getEvent().detail(Details.AUTH_METHOD, "auth_method");

	String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE);
	if (!Validation.isBlank(captcha)) {
		AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
		String secret = captchaConfig.getConfig().get(SITE_SECRET);

		success = validateRecaptcha(context, success, captcha, secret);
	}
	if (success) {
		super.action(context);
	} else {
		errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED));
		formData.remove(G_RECAPTCHA_RESPONSE);
		// context.error(Errors.INVALID_REGISTRATION);
		// context.validationError(formData, errors);
		// context.excludeOtherErrors();
		return;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("action(AuthenticationFlowContext) - end");
	}
}
 
Example 11
Source File: SessionPropagationAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private String getConfigProperty(AuthenticationFlowContext context, String key, String defaultValue) {

        if (context.getAuthenticatorConfig() == null) {
            return defaultValue;
        }

        Map<String, String> config = context.getAuthenticatorConfig().getConfig();
        if (config == null) {
            return defaultValue;
        }

        return config.getOrDefault(key, defaultValue);
    }
 
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
private String getConfigSettingOrDefault(AuthenticationFlowContext context, String key, String defaultValue) {

        AuthenticatorConfigModel authenticatorConfig = context.getAuthenticatorConfig();
        if (authenticatorConfig == null) {
            return defaultValue;
        }
        Map<String, String> config = authenticatorConfig.getConfig();
        if (config == null) {
            return defaultValue;
        }
        return config.getOrDefault(key, defaultValue);
    }
 
Example 14
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 15
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 16
Source File: ScriptBasedAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected AuthenticatorConfigModel getAuthenticatorConfig(AuthenticationFlowContext context) {
    return context.getAuthenticatorConfig();
}
 
Example 17
Source File: IdpCreateUserIfUniqueAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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();
        }
    }
}