Search in sources :

Example 21 with IdentityBrokerException

use of org.keycloak.broker.provider.IdentityBrokerException in project keycloak by keycloak.

the class GoogleIdentityProvider method validateToken.

@Override
protected JsonWebToken validateToken(final String encodedToken, final boolean ignoreAudience) {
    JsonWebToken token = super.validateToken(encodedToken, ignoreAudience);
    String hostedDomain = ((GoogleIdentityProviderConfig) getConfig()).getHostedDomain();
    if (hostedDomain == null) {
        return token;
    }
    Object receivedHdParam = token.getOtherClaims().get(OIDC_PARAMETER_HOSTED_DOMAINS);
    if (receivedHdParam == null) {
        throw new IdentityBrokerException("Identity token does not contain hosted domain parameter.");
    }
    if (hostedDomain.equals("*") || hostedDomain.equals(receivedHdParam)) {
        return token;
    }
    throw new IdentityBrokerException("Hosted domain does not match.");
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) JsonWebToken(org.keycloak.representations.JsonWebToken)

Example 22 with IdentityBrokerException

use of org.keycloak.broker.provider.IdentityBrokerException in project keycloak by keycloak.

the class GitHubIdentityProvider method doGetFederatedIdentity.

@Override
protected BrokeredIdentityContext doGetFederatedIdentity(String accessToken) {
    try {
        JsonNode profile = SimpleHttp.doGet(PROFILE_URL, session).header("Authorization", "Bearer " + accessToken).asJson();
        BrokeredIdentityContext user = extractIdentityFromProfile(null, profile);
        if (user.getEmail() == null) {
            user.setEmail(searchEmail(accessToken));
        }
        return user;
    } catch (Exception e) {
        throw new IdentityBrokerException("Could not obtain user profile from github.", e);
    }
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) JsonNode(com.fasterxml.jackson.databind.JsonNode) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException)

Example 23 with IdentityBrokerException

use of org.keycloak.broker.provider.IdentityBrokerException in project keycloak by keycloak.

the class IdentityBrokerService method afterPostBrokerLoginFlow.

// Callback from LoginActionsService after postBrokerLogin flow is finished
@GET
@NoCache
@Path("/after-post-broker-login")
public Response afterPostBrokerLoginFlow(@QueryParam(LoginActionsService.SESSION_CODE) String code, @QueryParam("client_id") String clientId, @QueryParam(Constants.TAB_ID) String tabId) {
    AuthenticationSessionModel authenticationSession = parseSessionCode(code, clientId, tabId);
    try {
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authenticationSession, PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession. Note " + PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT + " was null");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authenticationSession);
        String wasFirstBrokerLoginNote = authenticationSession.getAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN);
        boolean wasFirstBrokerLogin = Boolean.parseBoolean(wasFirstBrokerLoginNote);
        // Ensure the post-broker-login flow was successfully finished
        String authStateNoteKey = PostBrokerLoginConstants.PBL_AUTH_STATE_PREFIX + context.getIdpConfig().getAlias();
        String authState = authenticationSession.getAuthNote(authStateNoteKey);
        if (!Boolean.parseBoolean(authState)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that post-broker-login flow was finished");
        }
        // remove notes
        authenticationSession.removeAuthNote(PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);
        authenticationSession.removeAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN);
        return afterPostBrokerLoginFlowSuccess(authenticationSession, context, wasFirstBrokerLogin);
    } catch (IdentityBrokerException e) {
        return redirectToErrorPage(authenticationSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 24 with IdentityBrokerException

use of org.keycloak.broker.provider.IdentityBrokerException in project keycloak by keycloak.

the class IdentityBrokerService method getEndpoint.

@Path("{provider_id}/endpoint")
public Object getEndpoint(@PathParam("provider_id") String providerId) {
    IdentityProvider identityProvider;
    try {
        identityProvider = getIdentityProvider(session, realmModel, providerId);
    } catch (IdentityBrokerException e) {
        throw new NotFoundException(e.getMessage());
    }
    Object callback = identityProvider.callback(realmModel, this, event);
    ResteasyProviderFactory.getInstance().injectProperties(callback);
    return callback;
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) NotFoundException(javax.ws.rs.NotFoundException) SocialIdentityProvider(org.keycloak.broker.social.SocialIdentityProvider) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) Path(javax.ws.rs.Path)

Example 25 with IdentityBrokerException

use of org.keycloak.broker.provider.IdentityBrokerException 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)

Aggregations

IdentityBrokerException (org.keycloak.broker.provider.IdentityBrokerException)27 IOException (java.io.IOException)13 BrokeredIdentityContext (org.keycloak.broker.provider.BrokeredIdentityContext)11 JsonNode (com.fasterxml.jackson.databind.JsonNode)8 OAuthErrorException (org.keycloak.OAuthErrorException)7 NotFoundException (javax.ws.rs.NotFoundException)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 ErrorResponseException (org.keycloak.services.ErrorResponseException)5 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Path (javax.ws.rs.Path)4 IdentityProvider (org.keycloak.broker.provider.IdentityProvider)4 SocialIdentityProvider (org.keycloak.broker.social.SocialIdentityProvider)4 IdentityProviderModel (org.keycloak.models.IdentityProviderModel)4 RoleModel (org.keycloak.models.RoleModel)4 JsonWebToken (org.keycloak.representations.JsonWebToken)4 ErrorPageException (org.keycloak.services.ErrorPageException)4 GET (javax.ws.rs.GET)3 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 ClientModel (org.keycloak.models.ClientModel)3