Search in sources :

Example 16 with FederatedIdentityModel

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

the class IdentityBrokerService method updateFederatedIdentity.

private void updateFederatedIdentity(BrokeredIdentityContext context, UserModel federatedUser) {
    FederatedIdentityModel federatedIdentityModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, context.getIdpConfig().getAlias());
    if (context.getIdpConfig().getSyncMode() == IdentityProviderSyncMode.FORCE) {
        setBasicUserAttributes(context, federatedUser);
    }
    // Skip DB write if tokens are null or equal
    updateToken(context, federatedUser, federatedIdentityModel);
    context.getIdp().updateBrokeredUser(session, realmModel, federatedUser, context);
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    realmModel.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).forEach(mapper -> {
        IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
        IdentityProviderMapperSyncModeDelegate.delegateUpdateBrokeredUser(session, realmModel, federatedUser, mapper, context, target);
    });
}
Also used : FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory)

Example 17 with FederatedIdentityModel

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

the class IdentityBrokerService method migrateFederatedIdentityId.

private void migrateFederatedIdentityId(BrokeredIdentityContext context, UserModel federatedUser) {
    FederatedIdentityModel identityModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, context.getIdpConfig().getAlias());
    FederatedIdentityModel migratedIdentityModel = new FederatedIdentityModel(identityModel, context.getId());
    // since ID is a partial key we need to recreate the identity
    session.users().removeFederatedIdentity(realmModel, federatedUser, identityModel.getIdentityProvider());
    session.users().addFederatedIdentity(realmModel, federatedUser, migratedIdentityModel);
    logger.debugf("Federated user ID was migrated from %s to %s", identityModel.getUserId(), migratedIdentityModel.getUserId());
}
Also used : FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel)

Example 18 with FederatedIdentityModel

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

the class IdentityBrokerService method afterFirstBrokerLogin.

private Response afterFirstBrokerLogin(AuthenticationSessionModel authSession) {
    try {
        this.event.detail(Details.CODE_ID, authSession.getParentSession().getId()).removeDetail("auth_method");
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authSession);
        String providerId = context.getIdpConfig().getAlias();
        event.detail(Details.IDENTITY_PROVIDER, providerId);
        event.detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
        // Ensure the first-broker-login flow was successfully finished
        String authProvider = authSession.getAuthNote(AbstractIdpAuthenticator.FIRST_BROKER_LOGIN_SUCCESS);
        if (authProvider == null || !authProvider.equals(providerId)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that first-broker-login flow was finished");
        }
        // firstBrokerLogin workflow finished. Removing note now
        authSession.removeAuthNote(AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        UserModel federatedUser = authSession.getAuthenticatedUser();
        if (federatedUser == null) {
            throw new IdentityBrokerException("Couldn't found authenticated federatedUser in authentication session");
        }
        event.user(federatedUser);
        event.detail(Details.USERNAME, federatedUser.getUsername());
        if (context.getIdpConfig().isAddReadTokenRoleOnCreate()) {
            ClientModel brokerClient = realmModel.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
            if (brokerClient == null) {
                throw new IdentityBrokerException("Client 'broker' not available. Maybe realm has not migrated to support the broker token exchange service");
            }
            RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
            federatedUser.grantRole(readTokenRole);
        }
        // Add federated identity link here
        FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(), context.getUsername(), context.getToken());
        session.users().addFederatedIdentity(realmModel, federatedUser, federatedIdentityModel);
        String isRegisteredNewUser = authSession.getAuthNote(AbstractIdpAuthenticator.BROKER_REGISTERED_NEW_USER);
        if (Boolean.parseBoolean(isRegisteredNewUser)) {
            logger.debugf("Registered new user '%s' after first login with identity provider '%s'. Identity provider username is '%s' . ", federatedUser.getUsername(), providerId, context.getUsername());
            context.getIdp().importNewUser(session, realmModel, federatedUser, context);
            KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
            realmModel.getIdentityProviderMappersByAliasStream(providerId).forEach(mapper -> {
                IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
                target.importNewUser(session, realmModel, federatedUser, mapper, context);
            });
            if (context.getIdpConfig().isTrustEmail() && !Validation.isBlank(federatedUser.getEmail()) && !Boolean.parseBoolean(authSession.getAuthNote(AbstractIdpAuthenticator.UPDATE_PROFILE_EMAIL_CHANGED))) {
                logger.debugf("Email verified automatically after registration of user '%s' through Identity provider '%s' ", federatedUser.getUsername(), context.getIdpConfig().getAlias());
                federatedUser.setEmailVerified(true);
            }
            event.event(EventType.REGISTER).detail(Details.REGISTER_METHOD, "broker").detail(Details.EMAIL, federatedUser.getEmail()).success();
        } else {
            logger.debugf("Linked existing keycloak user '%s' with identity provider '%s' . Identity provider username is '%s' .", federatedUser.getUsername(), providerId, context.getUsername());
            event.event(EventType.FEDERATED_IDENTITY_LINK).success();
            updateFederatedIdentity(context, federatedUser);
        }
        return finishOrRedirectToPostBrokerLogin(authSession, context, true);
    } catch (Exception e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) RoleModel(org.keycloak.models.RoleModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) OAuthErrorException(org.keycloak.OAuthErrorException) NotFoundException(javax.ws.rs.NotFoundException) ErrorPageException(org.keycloak.services.ErrorPageException)

Example 19 with FederatedIdentityModel

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

the class IdentityBrokerService method performAccountLinking.

private Response performAccountLinking(AuthenticationSessionModel authSession, UserSessionModel userSession, BrokeredIdentityContext context, FederatedIdentityModel newModel, UserModel federatedUser) {
    logger.debugf("Will try to link identity provider [%s] to user [%s]", context.getIdpConfig().getAlias(), userSession.getUser().getUsername());
    this.event.event(EventType.FEDERATED_IDENTITY_LINK);
    UserModel authenticatedUser = userSession.getUser();
    authSession.setAuthenticatedUser(authenticatedUser);
    if (federatedUser != null && !authenticatedUser.getId().equals(federatedUser.getId())) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.IDENTITY_PROVIDER_ALREADY_LINKED, context.getIdpConfig().getAlias());
    }
    if (!authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT))) {
        return redirectToErrorPage(authSession, Response.Status.FORBIDDEN, Messages.INSUFFICIENT_PERMISSION);
    }
    if (!authenticatedUser.isEnabled()) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.ACCOUNT_DISABLED);
    }
    if (federatedUser != null) {
        if (context.getIdpConfig().isStoreToken()) {
            FederatedIdentityModel oldModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, context.getIdpConfig().getAlias());
            if (!ObjectUtil.isEqualOrBothNull(context.getToken(), oldModel.getToken())) {
                this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, newModel);
                if (isDebugEnabled()) {
                    logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
                }
            }
        }
    } else {
        this.session.users().addFederatedIdentity(this.realmModel, authenticatedUser, newModel);
    }
    context.getIdp().authenticationFinished(authSession, context);
    AuthenticationManager.setClientScopesInSession(authSession);
    TokenManager.attachAuthenticationSession(session, userSession, authSession);
    if (isDebugEnabled()) {
        logger.debugf("Linking account [%s] from identity provider [%s] to user [%s].", newModel, context.getIdpConfig().getAlias(), authenticatedUser);
    }
    this.event.user(authenticatedUser).detail(Details.USERNAME, authenticatedUser.getUsername()).detail(Details.IDENTITY_PROVIDER, newModel.getIdentityProvider()).detail(Details.IDENTITY_PROVIDER_USERNAME, newModel.getUserName()).success();
    // Maybe broker logout should be rather always skiped in case of broker-linking
    if (userSession.getNote(Details.IDENTITY_PROVIDER) == null) {
        userSession.setNote(Details.IDENTITY_PROVIDER, context.getIdpConfig().getAlias());
        userSession.setNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    }
    return Response.status(302).location(UriBuilder.fromUri(authSession.getRedirectUri()).build()).build();
}
Also used : UserModel(org.keycloak.models.UserModel) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel)

Example 20 with FederatedIdentityModel

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

the class RepresentationToModel method createFederatedIdentities.

public static void createFederatedIdentities(UserRepresentation userRep, KeycloakSession session, RealmModel realm, UserModel user) {
    if (userRep.getFederatedIdentities() != null) {
        for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
            FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
            session.users().addFederatedIdentity(realm, user, mappingModel);
        }
    }
}
Also used : FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation)

Aggregations

FederatedIdentityModel (org.keycloak.models.FederatedIdentityModel)22 UserModel (org.keycloak.models.UserModel)6 IOException (java.io.IOException)4 Path (javax.ws.rs.Path)4 NotFoundException (javax.ws.rs.NotFoundException)3 Produces (javax.ws.rs.Produces)3 IdentityProviderMapper (org.keycloak.broker.provider.IdentityProviderMapper)3 ClientModel (org.keycloak.models.ClientModel)3 IdentityProviderModel (org.keycloak.models.IdentityProviderModel)3 KeycloakSessionFactory (org.keycloak.models.KeycloakSessionFactory)3 URI (java.net.URI)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 GET (javax.ws.rs.GET)2 POST (javax.ws.rs.POST)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 Response (javax.ws.rs.core.Response)2 SerializedBrokeredIdentityContext (org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext)2