Search in sources :

Example 21 with IdentityProviderModel

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

the class IdentityProvidersResource method getIdentityProvider.

@Path("instances/{alias}")
public IdentityProviderResource getIdentityProvider(@PathParam("alias") String alias) {
    this.auth.realm().requireViewIdentityProviders();
    IdentityProviderModel identityProviderModel = this.realm.getIdentityProvidersStream().filter(p -> Objects.equals(p.getAlias(), alias) || Objects.equals(p.getInternalId(), alias)).findFirst().orElse(null);
    IdentityProviderResource identityProviderResource = new IdentityProviderResource(this.auth, realm, session, identityProviderModel, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(identityProviderResource);
    return identityProviderResource;
}
Also used : IdentityProviderModel(org.keycloak.models.IdentityProviderModel) Path(javax.ws.rs.Path)

Example 22 with IdentityProviderModel

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

the class IdentityProviderResource method lookUpProviderIdByAlias.

// sets internalId to IdentityProvider based on alias
private static void lookUpProviderIdByAlias(RealmModel realm, IdentityProviderRepresentation providerRep) {
    IdentityProviderModel identityProviderModel = realm.getIdentityProvidersStream().filter(p -> Objects.equals(p.getAlias(), providerRep.getAlias())).findFirst().orElseThrow(NotFoundException::new);
    providerRep.setInternalId(identityProviderModel.getInternalId());
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) IdentityProviderModel(org.keycloak.models.IdentityProviderModel)

Example 23 with IdentityProviderModel

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

the class IdentityProviderResource method updateIdpFromRep.

private void updateIdpFromRep(IdentityProviderRepresentation providerRep, RealmModel realm, KeycloakSession session) {
    String internalId = providerRep.getInternalId();
    String newProviderId = providerRep.getAlias();
    String oldProviderId = getProviderIdByInternalId(realm, internalId);
    if (oldProviderId == null) {
        lookUpProviderIdByAlias(realm, providerRep);
    }
    IdentityProviderModel updated = RepresentationToModel.toModel(realm, providerRep, session);
    if (updated.getConfig() != null && ComponentRepresentation.SECRET_VALUE.equals(updated.getConfig().get("clientSecret"))) {
        updated.getConfig().put("clientSecret", identityProviderModel.getConfig() != null ? identityProviderModel.getConfig().get("clientSecret") : null);
    }
    realm.updateIdentityProvider(updated);
    if (oldProviderId != null && !oldProviderId.equals(newProviderId)) {
        // Admin changed the ID (alias) of identity provider. We must update all clients and users
        logger.debug("Changing providerId in all clients and linked users. oldProviderId=" + oldProviderId + ", newProviderId=" + newProviderId);
        updateUsersAfterProviderAliasChange(session.users().getUsersStream(realm, false), oldProviderId, newProviderId, realm, session);
    }
}
Also used : IdentityProviderModel(org.keycloak.models.IdentityProviderModel)

Example 24 with IdentityProviderModel

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

the class IdentityProvidersPartialImport method create.

@Override
public void create(RealmModel realm, KeycloakSession session, IdentityProviderRepresentation idpRep) {
    idpRep.setInternalId(KeycloakModelUtils.generateId());
    IdentityProviderModel identityProvider = RepresentationToModel.toModel(realm, idpRep, session);
    realm.addIdentityProvider(identityProvider);
}
Also used : IdentityProviderModel(org.keycloak.models.IdentityProviderModel)

Example 25 with IdentityProviderModel

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

the class IdentityBrokerService method authenticated.

public Response authenticated(BrokeredIdentityContext context) {
    IdentityProviderModel identityProviderConfig = context.getIdpConfig();
    AuthenticationSessionModel authenticationSession = context.getAuthenticationSession();
    String providerId = identityProviderConfig.getAlias();
    if (!identityProviderConfig.isStoreToken()) {
        if (isDebugEnabled()) {
            logger.debugf("Token will not be stored for identity provider [%s].", providerId);
        }
        context.setToken(null);
    }
    StatusResponseType loginResponse = (StatusResponseType) context.getContextData().get(SAMLEndpoint.SAML_LOGIN_RESPONSE);
    if (loginResponse != null) {
        for (Iterator<SamlAuthenticationPreprocessor> it = SamlSessionUtils.getSamlAuthenticationPreprocessorIterator(session); it.hasNext(); ) {
            loginResponse = it.next().beforeProcessingLoginResponse(loginResponse, authenticationSession);
        }
    }
    session.getContext().setClient(authenticationSession.getClient());
    context.getIdp().preprocessFederatedIdentity(session, realmModel, context);
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    realmModel.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).forEach(mapper -> {
        IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
        target.preprocessFederatedIdentity(session, realmModel, mapper, context);
    });
    FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(providerId, context.getId(), context.getUsername(), context.getToken());
    this.event.event(EventType.IDENTITY_PROVIDER_LOGIN).detail(Details.REDIRECT_URI, authenticationSession.getRedirectUri()).detail(Details.IDENTITY_PROVIDER, providerId).detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    UserModel federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
    boolean shouldMigrateId = false;
    // try to find the user using legacy ID
    if (federatedUser == null && context.getLegacyId() != null) {
        federatedIdentityModel = new FederatedIdentityModel(federatedIdentityModel, context.getLegacyId());
        federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
        shouldMigrateId = true;
    }
    // Check if federatedUser is already authenticated (this means linking social into existing federatedUser account)
    UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authenticationSession);
    if (shouldPerformAccountLinking(authenticationSession, userSession, providerId)) {
        return performAccountLinking(authenticationSession, userSession, context, federatedIdentityModel, federatedUser);
    }
    if (federatedUser == null) {
        logger.debugf("Federated user not found for provider '%s' and broker username '%s'", providerId, context.getUsername());
        String username = context.getModelUsername();
        if (username == null) {
            if (this.realmModel.isRegistrationEmailAsUsername() && !Validation.isBlank(context.getEmail())) {
                username = context.getEmail();
            } else if (context.getUsername() == null) {
                username = context.getIdpConfig().getAlias() + "." + context.getId();
            } else {
                username = context.getUsername();
            }
        }
        username = username.trim();
        context.setModelUsername(username);
        SerializedBrokeredIdentityContext ctx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (ctx0 != null) {
            SerializedBrokeredIdentityContext ctx1 = SerializedBrokeredIdentityContext.serialize(context);
            ctx1.saveToAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
            logger.warnv("Nested first broker flow detected: {0} -> {1}", ctx0.getIdentityProviderId(), ctx1.getIdentityProviderId());
            logger.debug("Resuming last execution");
            URI redirect = new AuthenticationFlowURLHelper(session, realmModel, session.getContext().getUri()).getLastExecutionUrl(authenticationSession);
            return Response.status(Status.FOUND).location(redirect).build();
        }
        logger.debug("Redirecting to flow for firstBrokerLogin");
        boolean forwardedPassiveLogin = "true".equals(authenticationSession.getAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN));
        // Redirect to firstBrokerLogin after successful login and ensure that previous authentication state removed
        AuthenticationProcessor.resetFlow(authenticationSession, LoginActionsService.FIRST_BROKER_LOGIN_PATH);
        // Set the FORWARDED_PASSIVE_LOGIN note (if needed) after resetting the session so it is not lost.
        if (forwardedPassiveLogin) {
            authenticationSession.setAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN, "true");
        }
        SerializedBrokeredIdentityContext ctx = SerializedBrokeredIdentityContext.serialize(context);
        ctx.saveToAuthenticationSession(authenticationSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        URI redirect = LoginActionsService.firstBrokerLoginProcessor(session.getContext().getUri()).queryParam(Constants.CLIENT_ID, authenticationSession.getClient().getClientId()).queryParam(Constants.TAB_ID, authenticationSession.getTabId()).build(realmModel.getName());
        return Response.status(302).location(redirect).build();
    } else {
        Response response = validateUser(authenticationSession, federatedUser, realmModel);
        if (response != null) {
            return response;
        }
        updateFederatedIdentity(context, federatedUser);
        if (shouldMigrateId) {
            migrateFederatedIdentityId(context, federatedUser);
        }
        authenticationSession.setAuthenticatedUser(federatedUser);
        return finishOrRedirectToPostBrokerLogin(authenticationSession, context, false);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) AuthenticationFlowURLHelper(org.keycloak.services.util.AuthenticationFlowURLHelper) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) URI(java.net.URI) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) UserModel(org.keycloak.models.UserModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) SamlAuthenticationPreprocessor(org.keycloak.protocol.saml.preprocessor.SamlAuthenticationPreprocessor)

Aggregations

IdentityProviderModel (org.keycloak.models.IdentityProviderModel)32 RealmModel (org.keycloak.models.RealmModel)10 Response (javax.ws.rs.core.Response)8 IdentityProvider (org.keycloak.broker.provider.IdentityProvider)8 KeycloakSession (org.keycloak.models.KeycloakSession)6 UserModel (org.keycloak.models.UserModel)6 NotFoundException (javax.ws.rs.NotFoundException)5 Path (javax.ws.rs.Path)5 Test (org.junit.Test)5 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)5 IOException (java.io.IOException)4 Map (java.util.Map)4 OAuthErrorException (org.keycloak.OAuthErrorException)4 IdentityBrokerException (org.keycloak.broker.provider.IdentityBrokerException)4 IdentityProviderFactory (org.keycloak.broker.provider.IdentityProviderFactory)4 SocialIdentityProvider (org.keycloak.broker.social.SocialIdentityProvider)4 ClientModel (org.keycloak.models.ClientModel)4 FederatedIdentityModel (org.keycloak.models.FederatedIdentityModel)4 ErrorResponse (org.keycloak.services.ErrorResponse)4 URI (java.net.URI)3