Search in sources :

Example 6 with WebAuthnPolicy

use of org.keycloak.models.WebAuthnPolicy in project keycloak by keycloak.

the class WebAuthnRegister method processAction.

@Override
public void processAction(RequiredActionContext context) {
    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();
    String isSetRetry = params.getFirst(WebAuthnConstants.IS_SET_RETRY);
    if (isSetRetry != null && !isSetRetry.isEmpty()) {
        requiredActionChallenge(context);
        return;
    }
    context.getEvent().detail(Details.CREDENTIAL_TYPE, getCredentialType());
    // receive error from navigator.credentials.create()
    String errorMsgFromWebAuthnApi = params.getFirst(WebAuthnConstants.ERROR);
    if (errorMsgFromWebAuthnApi != null && !errorMsgFromWebAuthnApi.isEmpty()) {
        setErrorResponse(context, WEBAUTHN_ERROR_REGISTER_VERIFICATION, errorMsgFromWebAuthnApi);
        return;
    }
    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = policy.getRpId();
    if (rpId == null || rpId.isEmpty())
        rpId = context.getUriInfo().getBaseUri().getHost();
    String label = params.getFirst(WebAuthnConstants.AUTHENTICATOR_LABEL);
    byte[] clientDataJSON = Base64.getUrlDecoder().decode(params.getFirst(WebAuthnConstants.CLIENT_DATA_JSON));
    byte[] attestationObject = Base64.getUrlDecoder().decode(params.getFirst(WebAuthnConstants.ATTESTATION_OBJECT));
    String publicKeyCredentialId = params.getFirst(WebAuthnConstants.PUBLIC_KEY_CREDENTIAL_ID);
    Origin origin = new Origin(UriUtils.getOrigin(context.getUriInfo().getBaseUri()));
    Challenge challenge = new DefaultChallenge(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE));
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    // check User Verification by considering a malicious user might modify the result of calling WebAuthn API
    boolean isUserVerificationRequired = policy.getUserVerificationRequirement().equals(WebAuthnConstants.OPTION_REQUIRED);
    final String transportsParam = params.getFirst(WebAuthnConstants.TRANSPORTS);
    RegistrationRequest registrationRequest;
    if (StringUtil.isNotBlank(transportsParam)) {
        final Set<String> transports = new HashSet<>(Arrays.asList(transportsParam.split(",")));
        registrationRequest = new RegistrationRequest(attestationObject, clientDataJSON, transports);
    } else {
        registrationRequest = new RegistrationRequest(attestationObject, clientDataJSON);
    }
    RegistrationParameters registrationParameters = new RegistrationParameters(serverProperty, isUserVerificationRequired);
    WebAuthnRegistrationManager webAuthnRegistrationManager = createWebAuthnRegistrationManager();
    try {
        // parse
        RegistrationData registrationData = webAuthnRegistrationManager.parse(registrationRequest);
        // validate
        webAuthnRegistrationManager.validate(registrationData, registrationParameters);
        showInfoAfterWebAuthnApiCreate(registrationData);
        checkAcceptedAuthenticator(registrationData, policy);
        WebAuthnCredentialModelInput credential = new WebAuthnCredentialModelInput(getCredentialType());
        credential.setAttestedCredentialData(registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData());
        credential.setCount(registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
        credential.setAttestationStatementFormat(registrationData.getAttestationObject().getFormat());
        credential.setTransports(registrationData.getTransports());
        // Save new webAuthn credential
        WebAuthnCredentialProvider webAuthnCredProvider = (WebAuthnCredentialProvider) this.session.getProvider(CredentialProvider.class, getCredentialProviderId());
        WebAuthnCredentialModel newCredentialModel = webAuthnCredProvider.getCredentialModelFromCredentialInput(credential, label);
        webAuthnCredProvider.createCredential(context.getRealm(), context.getUser(), newCredentialModel);
        String aaguid = newCredentialModel.getWebAuthnCredentialData().getAaguid();
        logger.debugv("WebAuthn credential registration success for user {0}. credentialType = {1}, publicKeyCredentialId = {2}, publicKeyCredentialLabel = {3}, publicKeyCredentialAAGUID = {4}", context.getUser().getUsername(), getCredentialType(), publicKeyCredentialId, label, aaguid);
        webAuthnCredProvider.dumpCredentialModel(newCredentialModel, credential);
        context.getEvent().detail(WebAuthnConstants.PUBKEY_CRED_ID_ATTR, publicKeyCredentialId).detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, label).detail(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, aaguid);
        context.success();
    } catch (WebAuthnException wae) {
        if (logger.isDebugEnabled())
            logger.debug(wae.getMessage(), wae);
        setErrorResponse(context, WEBAUTHN_ERROR_REGISTRATION, wae.getMessage());
        return;
    } catch (Exception e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        setErrorResponse(context, WEBAUTHN_ERROR_REGISTRATION, e.getMessage());
        return;
    }
}
Also used : Origin(com.webauthn4j.data.client.Origin) RegistrationData(com.webauthn4j.data.RegistrationData) ServerProperty(com.webauthn4j.server.ServerProperty) WebAuthnCredentialModelInput(org.keycloak.credential.WebAuthnCredentialModelInput) WebAuthnCredentialProvider(org.keycloak.credential.WebAuthnCredentialProvider) RegistrationRequest(com.webauthn4j.data.RegistrationRequest) WebAuthnException(com.webauthn4j.util.exception.WebAuthnException) Challenge(com.webauthn4j.data.client.challenge.Challenge) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) WebAuthnCredentialModel(org.keycloak.models.credential.WebAuthnCredentialModel) WebAuthnException(com.webauthn4j.util.exception.WebAuthnException) WebAuthnPolicy(org.keycloak.models.WebAuthnPolicy) WebAuthnRegistrationManager(com.webauthn4j.WebAuthnRegistrationManager) WebAuthnCredentialProvider(org.keycloak.credential.WebAuthnCredentialProvider) CredentialProvider(org.keycloak.credential.CredentialProvider) RegistrationParameters(com.webauthn4j.data.RegistrationParameters) HashSet(java.util.HashSet)

Example 7 with WebAuthnPolicy

use of org.keycloak.models.WebAuthnPolicy in project keycloak by keycloak.

the class WebAuthnAuthenticator method getRpID.

protected String getRpID(AuthenticationFlowContext context) {
    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = policy.getRpId();
    if (rpId == null || rpId.isEmpty())
        rpId = context.getUriInfo().getBaseUri().getHost();
    return rpId;
}
Also used : WebAuthnPolicy(org.keycloak.models.WebAuthnPolicy)

Example 8 with WebAuthnPolicy

use of org.keycloak.models.WebAuthnPolicy in project keycloak by keycloak.

the class RepresentationToModel method importRealm.

public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm, boolean skipUserDependent) {
    convertDeprecatedSocialProviders(rep);
    convertDeprecatedApplications(session, rep);
    convertDeprecatedClientTemplates(rep);
    newRealm.setName(rep.getRealm());
    if (rep.getDisplayName() != null)
        newRealm.setDisplayName(rep.getDisplayName());
    if (rep.getDisplayNameHtml() != null)
        newRealm.setDisplayNameHtml(rep.getDisplayNameHtml());
    if (rep.isEnabled() != null)
        newRealm.setEnabled(rep.isEnabled());
    if (rep.isUserManagedAccessAllowed() != null)
        newRealm.setUserManagedAccessAllowed(rep.isUserManagedAccessAllowed());
    if (rep.isBruteForceProtected() != null)
        newRealm.setBruteForceProtected(rep.isBruteForceProtected());
    if (rep.isPermanentLockout() != null)
        newRealm.setPermanentLockout(rep.isPermanentLockout());
    if (rep.getMaxFailureWaitSeconds() != null)
        newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
    if (rep.getMinimumQuickLoginWaitSeconds() != null)
        newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
    if (rep.getWaitIncrementSeconds() != null)
        newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
    if (rep.getQuickLoginCheckMilliSeconds() != null)
        newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
    if (rep.getMaxDeltaTimeSeconds() != null)
        newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
    if (rep.getFailureFactor() != null)
        newRealm.setFailureFactor(rep.getFailureFactor());
    if (rep.isEventsEnabled() != null)
        newRealm.setEventsEnabled(rep.isEventsEnabled());
    if (rep.getEnabledEventTypes() != null)
        newRealm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
    if (rep.getEventsExpiration() != null)
        newRealm.setEventsExpiration(rep.getEventsExpiration());
    if (rep.getEventsListeners() != null)
        newRealm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
    if (rep.isAdminEventsEnabled() != null)
        newRealm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
    if (rep.isAdminEventsDetailsEnabled() != null)
        newRealm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
    if (rep.getNotBefore() != null)
        newRealm.setNotBefore(rep.getNotBefore());
    if (rep.getDefaultSignatureAlgorithm() != null)
        newRealm.setDefaultSignatureAlgorithm(rep.getDefaultSignatureAlgorithm());
    else
        newRealm.setDefaultSignatureAlgorithm(Constants.DEFAULT_SIGNATURE_ALGORITHM);
    if (rep.getRevokeRefreshToken() != null)
        newRealm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
    else
        newRealm.setRevokeRefreshToken(false);
    if (rep.getRefreshTokenMaxReuse() != null)
        newRealm.setRefreshTokenMaxReuse(rep.getRefreshTokenMaxReuse());
    else
        newRealm.setRefreshTokenMaxReuse(0);
    if (rep.getAccessTokenLifespan() != null)
        newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
    else
        newRealm.setAccessTokenLifespan(300);
    if (rep.getAccessTokenLifespanForImplicitFlow() != null)
        newRealm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
    else
        newRealm.setAccessTokenLifespanForImplicitFlow(Constants.DEFAULT_ACCESS_TOKEN_LIFESPAN_FOR_IMPLICIT_FLOW_TIMEOUT);
    if (rep.getSsoSessionIdleTimeout() != null)
        newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
    else
        newRealm.setSsoSessionIdleTimeout(1800);
    if (rep.getSsoSessionMaxLifespan() != null)
        newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
    else
        newRealm.setSsoSessionMaxLifespan(36000);
    if (rep.getSsoSessionMaxLifespanRememberMe() != null)
        newRealm.setSsoSessionMaxLifespanRememberMe(rep.getSsoSessionMaxLifespanRememberMe());
    if (rep.getSsoSessionIdleTimeoutRememberMe() != null)
        newRealm.setSsoSessionIdleTimeoutRememberMe(rep.getSsoSessionIdleTimeoutRememberMe());
    if (rep.getOfflineSessionIdleTimeout() != null)
        newRealm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
    else
        newRealm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
    // KEYCLOAK-7688 Offline Session Max for Offline Token
    if (rep.getOfflineSessionMaxLifespanEnabled() != null)
        newRealm.setOfflineSessionMaxLifespanEnabled(rep.getOfflineSessionMaxLifespanEnabled());
    else
        newRealm.setOfflineSessionMaxLifespanEnabled(false);
    if (rep.getOfflineSessionMaxLifespan() != null)
        newRealm.setOfflineSessionMaxLifespan(rep.getOfflineSessionMaxLifespan());
    else
        newRealm.setOfflineSessionMaxLifespan(Constants.DEFAULT_OFFLINE_SESSION_MAX_LIFESPAN);
    if (rep.getClientSessionIdleTimeout() != null)
        newRealm.setClientSessionIdleTimeout(rep.getClientSessionIdleTimeout());
    if (rep.getClientSessionMaxLifespan() != null)
        newRealm.setClientSessionMaxLifespan(rep.getClientSessionMaxLifespan());
    if (rep.getClientOfflineSessionIdleTimeout() != null)
        newRealm.setClientOfflineSessionIdleTimeout(rep.getClientOfflineSessionIdleTimeout());
    if (rep.getClientOfflineSessionMaxLifespan() != null)
        newRealm.setClientOfflineSessionMaxLifespan(rep.getClientOfflineSessionMaxLifespan());
    if (rep.getAccessCodeLifespan() != null)
        newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
    else
        newRealm.setAccessCodeLifespan(60);
    if (rep.getAccessCodeLifespanUserAction() != null)
        newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
    else
        newRealm.setAccessCodeLifespanUserAction(300);
    if (rep.getAccessCodeLifespanLogin() != null)
        newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
    else
        newRealm.setAccessCodeLifespanLogin(1800);
    if (rep.getActionTokenGeneratedByAdminLifespan() != null)
        newRealm.setActionTokenGeneratedByAdminLifespan(rep.getActionTokenGeneratedByAdminLifespan());
    else
        newRealm.setActionTokenGeneratedByAdminLifespan(12 * 60 * 60);
    if (rep.getActionTokenGeneratedByUserLifespan() != null)
        newRealm.setActionTokenGeneratedByUserLifespan(rep.getActionTokenGeneratedByUserLifespan());
    else
        newRealm.setActionTokenGeneratedByUserLifespan(newRealm.getAccessCodeLifespanUserAction());
    // OAuth 2.0 Device Authorization Grant
    OAuth2DeviceConfig deviceConfig = newRealm.getOAuth2DeviceConfig();
    deviceConfig.setOAuth2DeviceCodeLifespan(rep.getOAuth2DeviceCodeLifespan());
    deviceConfig.setOAuth2DevicePollingInterval(rep.getOAuth2DevicePollingInterval());
    if (rep.getSslRequired() != null)
        newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
    if (rep.isRegistrationAllowed() != null)
        newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
    if (rep.isRegistrationEmailAsUsername() != null)
        newRealm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
    if (rep.isRememberMe() != null)
        newRealm.setRememberMe(rep.isRememberMe());
    if (rep.isVerifyEmail() != null)
        newRealm.setVerifyEmail(rep.isVerifyEmail());
    if (rep.isLoginWithEmailAllowed() != null)
        newRealm.setLoginWithEmailAllowed(rep.isLoginWithEmailAllowed());
    if (rep.isDuplicateEmailsAllowed() != null)
        newRealm.setDuplicateEmailsAllowed(rep.isDuplicateEmailsAllowed());
    if (rep.isResetPasswordAllowed() != null)
        newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
    if (rep.isEditUsernameAllowed() != null)
        newRealm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
    if (rep.getLoginTheme() != null)
        newRealm.setLoginTheme(rep.getLoginTheme());
    if (rep.getAccountTheme() != null)
        newRealm.setAccountTheme(rep.getAccountTheme());
    if (rep.getAdminTheme() != null)
        newRealm.setAdminTheme(rep.getAdminTheme());
    if (rep.getEmailTheme() != null)
        newRealm.setEmailTheme(rep.getEmailTheme());
    // todo remove this stuff as its all deprecated
    if (rep.getRequiredCredentials() != null) {
        for (String requiredCred : rep.getRequiredCredentials()) {
            newRealm.addRequiredCredential(requiredCred);
        }
    } else {
        newRealm.addRequiredCredential(CredentialRepresentation.PASSWORD);
    }
    if (rep.getPasswordPolicy() != null)
        newRealm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
    if (rep.getOtpPolicyType() != null)
        newRealm.setOTPPolicy(toPolicy(rep));
    else
        newRealm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY);
    WebAuthnPolicy webAuthnPolicy = getWebAuthnPolicyTwoFactor(rep);
    newRealm.setWebAuthnPolicy(webAuthnPolicy);
    webAuthnPolicy = getWebAuthnPolicyPasswordless(rep);
    newRealm.setWebAuthnPolicyPasswordless(webAuthnPolicy);
    updateCibaSettings(rep, newRealm);
    updateParSettings(rep, newRealm);
    Map<String, String> mappedFlows = importAuthenticationFlows(newRealm, rep);
    if (rep.getRequiredActions() != null) {
        for (RequiredActionProviderRepresentation action : rep.getRequiredActions()) {
            RequiredActionProviderModel model = toModel(action);
            MigrationUtils.updateOTPRequiredAction(model);
            newRealm.addRequiredActionProvider(model);
        }
        DefaultRequiredActions.addDeleteAccountAction(newRealm);
    } else {
        DefaultRequiredActions.addActions(newRealm);
    }
    importIdentityProviders(rep, newRealm, session);
    importIdentityProviderMappers(rep, newRealm);
    Map<String, ClientScopeModel> clientScopes = new HashMap<>();
    if (rep.getClientScopes() != null) {
        clientScopes = createClientScopes(session, rep.getClientScopes(), newRealm);
    }
    if (rep.getDefaultDefaultClientScopes() != null) {
        for (String clientScopeName : rep.getDefaultDefaultClientScopes()) {
            ClientScopeModel clientScope = clientScopes.get(clientScopeName);
            if (clientScope != null) {
                newRealm.addDefaultClientScope(clientScope, true);
            } else {
                logger.warnf("Referenced client scope '%s' doesn't exist", clientScopeName);
            }
        }
    }
    if (rep.getDefaultOptionalClientScopes() != null) {
        for (String clientScopeName : rep.getDefaultOptionalClientScopes()) {
            ClientScopeModel clientScope = clientScopes.get(clientScopeName);
            if (clientScope != null) {
                newRealm.addDefaultClientScope(clientScope, false);
            } else {
                logger.warnf("Referenced client scope '%s' doesn't exist", clientScopeName);
            }
        }
    }
    Map<String, ClientModel> createdClients = new HashMap<>();
    if (rep.getClients() != null) {
        createdClients = createClients(session, rep, newRealm, mappedFlows);
    }
    importRoles(rep.getRoles(), newRealm);
    convertDeprecatedDefaultRoles(rep, newRealm);
    if (rep.getClientScopeMappings() != null) {
        for (Map.Entry<String, List<ScopeMappingRepresentation>> entry : rep.getClientScopeMappings().entrySet()) {
            ClientModel app = createdClients.computeIfAbsent(entry.getKey(), k -> newRealm.getClientByClientId(entry.getKey()));
            if (app == null) {
                throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
            }
            createClientScopeMappings(newRealm, app, entry.getValue());
        }
    }
    if (rep.getScopeMappings() != null) {
        Map<String, RoleModel> roleModelMap = newRealm.getRolesStream().collect(Collectors.toMap(RoleModel::getId, Function.identity()));
        for (ScopeMappingRepresentation scope : rep.getScopeMappings()) {
            ScopeContainerModel scopeContainer = getScopeContainerHavingScope(newRealm, scope);
            for (String roleString : scope.getRoles()) {
                final String roleStringTrimmed = roleString.trim();
                RoleModel role = roleModelMap.computeIfAbsent(roleStringTrimmed, k -> newRealm.getRole(roleStringTrimmed));
                if (role == null) {
                    role = newRealm.addRole(roleString);
                    roleModelMap.put(role.getId(), role);
                }
                scopeContainer.addScopeMapping(role);
            }
        }
    }
    if (rep.getSmtpServer() != null) {
        newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer()));
    }
    if (rep.getBrowserSecurityHeaders() != null) {
        newRealm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
    } else {
        newRealm.setBrowserSecurityHeaders(BrowserSecurityHeaders.realmDefaultHeaders);
    }
    if (rep.getComponents() != null) {
        MultivaluedHashMap<String, ComponentExportRepresentation> components = rep.getComponents();
        String parentId = newRealm.getId();
        importComponents(newRealm, components, parentId);
    }
    importUserFederationProvidersAndMappers(session, rep, newRealm);
    if (rep.getGroups() != null) {
        importGroups(newRealm, rep);
        if (rep.getDefaultGroups() != null) {
            for (String path : rep.getDefaultGroups()) {
                GroupModel found = KeycloakModelUtils.findGroupByPath(newRealm, path);
                if (found == null)
                    throw new RuntimeException("default group in realm rep doesn't exist: " + path);
                newRealm.addDefaultGroup(found);
            }
        }
    }
    if (rep.getUsers() != null) {
        for (UserRepresentation userRep : rep.getUsers()) {
            createUser(session, newRealm, userRep);
        }
    }
    if (rep.getFederatedUsers() != null) {
        for (UserRepresentation userRep : rep.getFederatedUsers()) {
            importFederatedUser(session, newRealm, userRep);
        }
    }
    if (!skipUserDependent) {
        importRealmAuthorizationSettings(rep, newRealm, session);
    }
    if (rep.isInternationalizationEnabled() != null) {
        newRealm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
    }
    if (rep.getSupportedLocales() != null) {
        newRealm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
    }
    if (rep.getDefaultLocale() != null) {
        newRealm.setDefaultLocale(rep.getDefaultLocale());
    }
    if (rep.getAttributes() != null) {
        for (Map.Entry<String, String> attr : rep.getAttributes().entrySet()) {
            newRealm.setAttribute(attr.getKey(), attr.getValue());
        }
    }
    if (newRealm.getComponentsStream(newRealm.getId(), KeyProvider.class.getName()).count() == 0) {
        if (rep.getPrivateKey() != null) {
            DefaultKeyProviders.createProviders(newRealm, rep.getPrivateKey(), rep.getCertificate());
        } else {
            DefaultKeyProviders.createProviders(newRealm);
        }
    }
}
Also used : KeyProvider(org.keycloak.keys.KeyProvider) OAuth2DeviceConfig(org.keycloak.models.OAuth2DeviceConfig) ScopeContainerModel(org.keycloak.models.ScopeContainerModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) GroupModel(org.keycloak.models.GroupModel) ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RequiredActionProviderRepresentation(org.keycloak.representations.idm.RequiredActionProviderRepresentation) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) ClientModel(org.keycloak.models.ClientModel) WebAuthnPolicy(org.keycloak.models.WebAuthnPolicy) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap)

Example 9 with WebAuthnPolicy

use of org.keycloak.models.WebAuthnPolicy in project keycloak by keycloak.

the class RepresentationToModel method updateRealm.

public static void updateRealm(RealmRepresentation rep, RealmModel realm, KeycloakSession session) {
    if (rep.getRealm() != null) {
        renameRealm(realm, rep.getRealm());
    }
    if (!Boolean.parseBoolean(rep.getAttributesOrEmpty().get("userProfileEnabled"))) {
        UserProfileProvider provider = session.getProvider(UserProfileProvider.class);
        provider.setConfiguration(null);
    }
    // Import attributes first, so the stuff saved directly on representation (displayName, bruteForce etc) has bigger priority
    if (rep.getAttributes() != null) {
        Set<String> attrsToRemove = new HashSet<>(realm.getAttributes().keySet());
        attrsToRemove.removeAll(rep.getAttributes().keySet());
        for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
            realm.setAttribute(entry.getKey(), entry.getValue());
        }
        for (String attr : attrsToRemove) {
            realm.removeAttribute(attr);
        }
    }
    if (rep.getDisplayName() != null)
        realm.setDisplayName(rep.getDisplayName());
    if (rep.getDisplayNameHtml() != null)
        realm.setDisplayNameHtml(rep.getDisplayNameHtml());
    if (rep.isEnabled() != null)
        realm.setEnabled(rep.isEnabled());
    if (rep.isUserManagedAccessAllowed() != null)
        realm.setUserManagedAccessAllowed(rep.isUserManagedAccessAllowed());
    if (rep.isBruteForceProtected() != null)
        realm.setBruteForceProtected(rep.isBruteForceProtected());
    if (rep.isPermanentLockout() != null)
        realm.setPermanentLockout(rep.isPermanentLockout());
    if (rep.getMaxFailureWaitSeconds() != null)
        realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
    if (rep.getMinimumQuickLoginWaitSeconds() != null)
        realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
    if (rep.getWaitIncrementSeconds() != null)
        realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
    if (rep.getQuickLoginCheckMilliSeconds() != null)
        realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
    if (rep.getMaxDeltaTimeSeconds() != null)
        realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
    if (rep.getFailureFactor() != null)
        realm.setFailureFactor(rep.getFailureFactor());
    if (rep.isRegistrationAllowed() != null)
        realm.setRegistrationAllowed(rep.isRegistrationAllowed());
    if (rep.isRegistrationEmailAsUsername() != null)
        realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
    if (rep.isRememberMe() != null)
        realm.setRememberMe(rep.isRememberMe());
    if (rep.isVerifyEmail() != null)
        realm.setVerifyEmail(rep.isVerifyEmail());
    if (rep.isLoginWithEmailAllowed() != null)
        realm.setLoginWithEmailAllowed(rep.isLoginWithEmailAllowed());
    if (rep.isDuplicateEmailsAllowed() != null)
        realm.setDuplicateEmailsAllowed(rep.isDuplicateEmailsAllowed());
    if (rep.isResetPasswordAllowed() != null)
        realm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
    if (rep.isEditUsernameAllowed() != null)
        realm.setEditUsernameAllowed(rep.isEditUsernameAllowed());
    if (rep.getSslRequired() != null)
        realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
    if (rep.getAccessCodeLifespan() != null)
        realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
    if (rep.getAccessCodeLifespanUserAction() != null)
        realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
    if (rep.getAccessCodeLifespanLogin() != null)
        realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
    if (rep.getActionTokenGeneratedByAdminLifespan() != null)
        realm.setActionTokenGeneratedByAdminLifespan(rep.getActionTokenGeneratedByAdminLifespan());
    if (rep.getActionTokenGeneratedByUserLifespan() != null)
        realm.setActionTokenGeneratedByUserLifespan(rep.getActionTokenGeneratedByUserLifespan());
    OAuth2DeviceConfig deviceConfig = realm.getOAuth2DeviceConfig();
    deviceConfig.setOAuth2DeviceCodeLifespan(rep.getOAuth2DeviceCodeLifespan());
    deviceConfig.setOAuth2DevicePollingInterval(rep.getOAuth2DevicePollingInterval());
    if (rep.getNotBefore() != null)
        realm.setNotBefore(rep.getNotBefore());
    if (rep.getDefaultSignatureAlgorithm() != null)
        realm.setDefaultSignatureAlgorithm(rep.getDefaultSignatureAlgorithm());
    if (rep.getRevokeRefreshToken() != null)
        realm.setRevokeRefreshToken(rep.getRevokeRefreshToken());
    if (rep.getRefreshTokenMaxReuse() != null)
        realm.setRefreshTokenMaxReuse(rep.getRefreshTokenMaxReuse());
    if (rep.getAccessTokenLifespan() != null)
        realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
    if (rep.getAccessTokenLifespanForImplicitFlow() != null)
        realm.setAccessTokenLifespanForImplicitFlow(rep.getAccessTokenLifespanForImplicitFlow());
    if (rep.getSsoSessionIdleTimeout() != null)
        realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
    if (rep.getSsoSessionMaxLifespan() != null)
        realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
    if (rep.getSsoSessionIdleTimeoutRememberMe() != null)
        realm.setSsoSessionIdleTimeoutRememberMe(rep.getSsoSessionIdleTimeoutRememberMe());
    if (rep.getSsoSessionMaxLifespanRememberMe() != null)
        realm.setSsoSessionMaxLifespanRememberMe(rep.getSsoSessionMaxLifespanRememberMe());
    if (rep.getOfflineSessionIdleTimeout() != null)
        realm.setOfflineSessionIdleTimeout(rep.getOfflineSessionIdleTimeout());
    // KEYCLOAK-7688 Offline Session Max for Offline Token
    if (rep.getOfflineSessionMaxLifespanEnabled() != null)
        realm.setOfflineSessionMaxLifespanEnabled(rep.getOfflineSessionMaxLifespanEnabled());
    if (rep.getOfflineSessionMaxLifespan() != null)
        realm.setOfflineSessionMaxLifespan(rep.getOfflineSessionMaxLifespan());
    if (rep.getClientSessionIdleTimeout() != null)
        realm.setClientSessionIdleTimeout(rep.getClientSessionIdleTimeout());
    if (rep.getClientSessionMaxLifespan() != null)
        realm.setClientSessionMaxLifespan(rep.getClientSessionMaxLifespan());
    if (rep.getClientOfflineSessionIdleTimeout() != null)
        realm.setClientOfflineSessionIdleTimeout(rep.getClientOfflineSessionIdleTimeout());
    if (rep.getClientOfflineSessionMaxLifespan() != null)
        realm.setClientOfflineSessionMaxLifespan(rep.getClientOfflineSessionMaxLifespan());
    if (rep.getRequiredCredentials() != null) {
        realm.updateRequiredCredentials(rep.getRequiredCredentials());
    }
    if (rep.getLoginTheme() != null)
        realm.setLoginTheme(rep.getLoginTheme());
    if (rep.getAccountTheme() != null)
        realm.setAccountTheme(rep.getAccountTheme());
    if (rep.getAdminTheme() != null)
        realm.setAdminTheme(rep.getAdminTheme());
    if (rep.getEmailTheme() != null)
        realm.setEmailTheme(rep.getEmailTheme());
    if (rep.isEventsEnabled() != null)
        realm.setEventsEnabled(rep.isEventsEnabled());
    if (rep.getEventsExpiration() != null)
        realm.setEventsExpiration(rep.getEventsExpiration());
    if (rep.getEventsListeners() != null)
        realm.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
    if (rep.getEnabledEventTypes() != null)
        realm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
    if (rep.isAdminEventsEnabled() != null)
        realm.setAdminEventsEnabled(rep.isAdminEventsEnabled());
    if (rep.isAdminEventsDetailsEnabled() != null)
        realm.setAdminEventsDetailsEnabled(rep.isAdminEventsDetailsEnabled());
    if (rep.getPasswordPolicy() != null)
        realm.setPasswordPolicy(PasswordPolicy.parse(session, rep.getPasswordPolicy()));
    if (rep.getOtpPolicyType() != null)
        realm.setOTPPolicy(toPolicy(rep));
    WebAuthnPolicy webAuthnPolicy = getWebAuthnPolicyTwoFactor(rep);
    realm.setWebAuthnPolicy(webAuthnPolicy);
    webAuthnPolicy = getWebAuthnPolicyPasswordless(rep);
    realm.setWebAuthnPolicyPasswordless(webAuthnPolicy);
    updateCibaSettings(rep, realm);
    updateParSettings(rep, realm);
    session.clientPolicy().updateRealmModelFromRepresentation(realm, rep);
    if (rep.getSmtpServer() != null) {
        Map<String, String> config = new HashMap(rep.getSmtpServer());
        if (rep.getSmtpServer().containsKey("password") && ComponentRepresentation.SECRET_VALUE.equals(rep.getSmtpServer().get("password"))) {
            String passwordValue = realm.getSmtpConfig() != null ? realm.getSmtpConfig().get("password") : null;
            config.put("password", passwordValue);
        }
        realm.setSmtpConfig(config);
    }
    if (rep.getBrowserSecurityHeaders() != null) {
        realm.setBrowserSecurityHeaders(rep.getBrowserSecurityHeaders());
    }
    if (rep.isInternationalizationEnabled() != null) {
        realm.setInternationalizationEnabled(rep.isInternationalizationEnabled());
    }
    if (rep.getSupportedLocales() != null) {
        realm.setSupportedLocales(new HashSet<String>(rep.getSupportedLocales()));
    }
    if (rep.getDefaultLocale() != null) {
        realm.setDefaultLocale(rep.getDefaultLocale());
    }
    if (rep.getBrowserFlow() != null) {
        realm.setBrowserFlow(realm.getFlowByAlias(rep.getBrowserFlow()));
    }
    if (rep.getRegistrationFlow() != null) {
        realm.setRegistrationFlow(realm.getFlowByAlias(rep.getRegistrationFlow()));
    }
    if (rep.getDirectGrantFlow() != null) {
        realm.setDirectGrantFlow(realm.getFlowByAlias(rep.getDirectGrantFlow()));
    }
    if (rep.getResetCredentialsFlow() != null) {
        realm.setResetCredentialsFlow(realm.getFlowByAlias(rep.getResetCredentialsFlow()));
    }
    if (rep.getClientAuthenticationFlow() != null) {
        realm.setClientAuthenticationFlow(realm.getFlowByAlias(rep.getClientAuthenticationFlow()));
    }
    if (rep.getDockerAuthenticationFlow() != null) {
        realm.setDockerAuthenticationFlow(realm.getFlowByAlias(rep.getDockerAuthenticationFlow()));
    }
}
Also used : OAuth2DeviceConfig(org.keycloak.models.OAuth2DeviceConfig) WebAuthnPolicy(org.keycloak.models.WebAuthnPolicy) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

WebAuthnPolicy (org.keycloak.models.WebAuthnPolicy)9 ArtifactBindingUtils.computeArtifactBindingIdentifierString (org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString)4 Challenge (com.webauthn4j.data.client.challenge.Challenge)3 DefaultChallenge (com.webauthn4j.data.client.challenge.DefaultChallenge)3 HashSet (java.util.HashSet)3 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)2 OAuth2DeviceConfig (org.keycloak.models.OAuth2DeviceConfig)2 UserModel (org.keycloak.models.UserModel)2 WebAuthnCredentialModel (org.keycloak.models.credential.WebAuthnCredentialModel)2 WebAuthnRegistrationManager (com.webauthn4j.WebAuthnRegistrationManager)1 RegistrationData (com.webauthn4j.data.RegistrationData)1 RegistrationParameters (com.webauthn4j.data.RegistrationParameters)1 RegistrationRequest (com.webauthn4j.data.RegistrationRequest)1 Origin (com.webauthn4j.data.client.Origin)1 ServerProperty (com.webauthn4j.server.ServerProperty)1 WebAuthnException (com.webauthn4j.util.exception.WebAuthnException)1 ArrayList (java.util.ArrayList)1