Search in sources :

Example 1 with ClientRegistrationResponse

use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.

the class ApplicationServiceImpl method renewClientSecret.

@Override
public ApplicationEntity renewClientSecret(String applicationId) {
    try {
        LOGGER.debug("Renew client secret for application {}", applicationId);
        Optional<Application> optApplicationToUpdate = applicationRepository.findById(applicationId);
        if (!optApplicationToUpdate.isPresent()) {
            throw new ApplicationNotFoundException(applicationId);
        }
        if (ApplicationStatus.ARCHIVED.equals(optApplicationToUpdate.get().getStatus())) {
            throw new ApplicationArchivedException(optApplicationToUpdate.get().getName());
        }
        // Check that client registration is enabled
        checkClientRegistrationEnabled();
        Application application = optApplicationToUpdate.get();
        ApplicationEntity applicationEntity = findById(applicationId);
        // Check that the application can be updated with a new client secret
        if (applicationEntity.getSettings().getoAuthClient() != null && applicationEntity.getSettings().getoAuthClient().isRenewClientSecretSupported()) {
            ClientRegistrationResponse registrationResponse = clientRegistrationService.renewClientSecret(application.getMetadata().get("registration_payload"));
            // Update application metadata
            Map<String, String> metadata = new HashMap<>();
            try {
                metadata.put("client_id", registrationResponse.getClientId());
                metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            application.setUpdatedAt(new Date());
            metadata.forEach((key, value) -> application.getMetadata().put(key, value));
            Application updatedApplication = applicationRepository.update(application);
            // Audit
            auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_UPDATED, updatedApplication.getUpdatedAt(), optApplicationToUpdate.get(), updatedApplication);
            return convert(Collections.singleton(updatedApplication)).iterator().next();
        }
        throw new ApplicationRenewClientSecretException(application.getName());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to renew client secret {}", applicationId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to renew client secret %s", applicationId), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ClientRegistrationResponse(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse) UuidString(io.gravitee.rest.api.service.common.UuidString) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with ClientRegistrationResponse

use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.

the class ApplicationServiceImpl method getSettings.

private ApplicationSettings getSettings(Application application) {
    final ApplicationSettings settings = new ApplicationSettings();
    if (application.getType() == ApplicationType.SIMPLE) {
        SimpleApplicationSettings simpleSettings = new SimpleApplicationSettings();
        if (application.getMetadata() != null) {
            if (application.getMetadata().get("client_id") != null) {
                simpleSettings.setClientId(application.getMetadata().get("client_id"));
            }
            if (application.getMetadata().get("type") != null) {
                simpleSettings.setType(application.getMetadata().get("type"));
            }
        }
        settings.setApp(simpleSettings);
    } else {
        OAuthClientSettings clientSettings = new OAuthClientSettings();
        if (application.getMetadata() != null) {
            try {
                final String registrationPayload = application.getMetadata().get("registration_payload");
                if (registrationPayload != null) {
                    final ClientRegistrationResponse registrationResponse = mapper.readValue(registrationPayload, ClientRegistrationResponse.class);
                    clientSettings.setClientId(registrationResponse.getClientId());
                    clientSettings.setClientSecret(registrationResponse.getClientSecret());
                    clientSettings.setClientUri(registrationResponse.getClientUri());
                    clientSettings.setApplicationType(registrationResponse.getApplicationType());
                    clientSettings.setLogoUri(registrationResponse.getLogoUri());
                    clientSettings.setResponseTypes(registrationResponse.getResponseTypes());
                    clientSettings.setRedirectUris(registrationResponse.getRedirectUris());
                    clientSettings.setGrantTypes(registrationResponse.getGrantTypes());
                }
                Iterator<ClientRegistrationProviderEntity> clientRegistrationProviderIte = clientRegistrationService.findAll().iterator();
                if (clientRegistrationProviderIte.hasNext()) {
                    clientSettings.setRenewClientSecretSupported(clientRegistrationProviderIte.next().isRenewClientSecretSupport());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        settings.setoAuthClient(clientSettings);
    }
    return settings;
}
Also used : ApplicationSettings(io.gravitee.rest.api.model.application.ApplicationSettings) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) OAuthClientSettings(io.gravitee.rest.api.model.application.OAuthClientSettings) ClientRegistrationResponse(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse) ClientRegistrationProviderEntity(io.gravitee.rest.api.model.configuration.application.registration.ClientRegistrationProviderEntity) UuidString(io.gravitee.rest.api.service.common.UuidString) IOException(java.io.IOException)

Example 3 with ClientRegistrationResponse

use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.

the class ApplicationServiceImpl method create.

@Override
public ApplicationEntity create(NewApplicationEntity newApplicationEntity, String userId, String environmentId) {
    LOGGER.debug("Create {} for user {}", newApplicationEntity, userId);
    // Check that only one settings is defined
    if (newApplicationEntity.getSettings().getApp() != null && newApplicationEntity.getSettings().getoAuthClient() != null) {
        throw new InvalidApplicationTypeException();
    }
    // Check that a type is defined
    if (newApplicationEntity.getSettings().getApp() == null && newApplicationEntity.getSettings().getoAuthClient() == null) {
        throw new InvalidApplicationTypeException();
    }
    // Create application metadata
    Map<String, String> metadata = new HashMap<>();
    // Create a simple "internal" application
    if (newApplicationEntity.getSettings().getApp() != null) {
        // If client registration is enabled, check that the simple type is allowed
        if (isClientRegistrationEnabled(environmentId) && !isApplicationTypeAllowed("simple", environmentId)) {
            throw new IllegalStateException("Application type 'simple' is not allowed");
        }
        // If clientId is set, check for uniqueness
        String clientId = newApplicationEntity.getSettings().getApp().getClientId();
        if (clientId != null && !clientId.trim().isEmpty()) {
            LOGGER.debug("Check that client_id is unique among all applications");
            try {
                final Set<Application> applications = applicationRepository.findAllByEnvironment(environmentId, ApplicationStatus.ACTIVE);
                final boolean alreadyExistingApp = applications.stream().anyMatch(app -> app.getMetadata() != null && clientId.equals(app.getMetadata().get("client_id")));
                if (alreadyExistingApp) {
                    LOGGER.error("An application already exists with the same client_id");
                    throw new ClientIdAlreadyExistsException(clientId);
                }
            } catch (TechnicalException ex) {
                LOGGER.error("An error occurs while trying to create {} for user {}", newApplicationEntity, userId, ex);
                throw new TechnicalManagementException("An error occurs while trying create " + newApplicationEntity + " for user " + userId, ex);
            }
        }
    } else {
        // Check that client registration is enabled
        checkClientRegistrationEnabled(environmentId);
        String appType = newApplicationEntity.getSettings().getoAuthClient().getApplicationType();
        // Check that the application_type is allowed
        if (!isApplicationTypeAllowed(appType, environmentId)) {
            throw new IllegalStateException("Application type '" + appType + "' is not allowed");
        }
        checkClientSettings(newApplicationEntity.getSettings().getoAuthClient());
        // Create an OAuth client
        ClientRegistrationResponse registrationResponse = clientRegistrationService.register(newApplicationEntity);
        try {
            metadata.put("client_id", registrationResponse.getClientId());
            metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    if (newApplicationEntity.getGroups() != null && !newApplicationEntity.getGroups().isEmpty()) {
        // throw a NotFoundException if the group doesn't exist
        groupService.findByIds(newApplicationEntity.getGroups());
    }
    Application application = convert(newApplicationEntity);
    application.setId(UuidString.generateRandom());
    application.setStatus(ApplicationStatus.ACTIVE);
    metadata.forEach((key, value) -> application.getMetadata().put(key, value));
    // Add Default groups
    Set<String> defaultGroups = groupService.findByEvent(GroupEvent.APPLICATION_CREATE).stream().map(GroupEntity::getId).collect(toSet());
    if (!defaultGroups.isEmpty() && application.getGroups() == null) {
        application.setGroups(defaultGroups);
    } else if (!defaultGroups.isEmpty()) {
        application.getGroups().addAll(defaultGroups);
    }
    // Set date fields
    application.setCreatedAt(new Date());
    application.setUpdatedAt(application.getCreatedAt());
    return createApplicationForEnvironment(userId, application, environmentId);
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ClientRegistrationResponse(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse) UuidString(io.gravitee.rest.api.service.common.UuidString) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 4 with ClientRegistrationResponse

use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.

the class ApplicationServiceImpl method update.

@Override
public ApplicationEntity update(String applicationId, UpdateApplicationEntity updateApplicationEntity) {
    try {
        LOGGER.debug("Update application {}", applicationId);
        if (updateApplicationEntity.getGroups() != null && !updateApplicationEntity.getGroups().isEmpty()) {
            // throw a NotFoundException if the group doesn't exist
            groupService.findByIds(updateApplicationEntity.getGroups());
        }
        Optional<Application> optApplicationToUpdate = applicationRepository.findById(applicationId);
        if (!optApplicationToUpdate.isPresent()) {
            throw new ApplicationNotFoundException(applicationId);
        }
        if (ApplicationStatus.ARCHIVED.equals(optApplicationToUpdate.get().getStatus())) {
            throw new ApplicationArchivedException(optApplicationToUpdate.get().getName());
        }
        // Check that only one settings is defined
        if (updateApplicationEntity.getSettings().getApp() != null && updateApplicationEntity.getSettings().getoAuthClient() != null) {
            throw new InvalidApplicationTypeException();
        }
        // Check that a type is defined
        if (updateApplicationEntity.getSettings().getApp() == null && updateApplicationEntity.getSettings().getoAuthClient() == null) {
            throw new InvalidApplicationTypeException();
        }
        // Update application metadata
        Map<String, String> metadata = new HashMap<>();
        // Update a simple application
        if (optApplicationToUpdate.get().getType() == ApplicationType.SIMPLE && updateApplicationEntity.getSettings().getApp() != null) {
            // If clientId is set, check for uniqueness
            String clientId = updateApplicationEntity.getSettings().getApp().getClientId();
            if (clientId != null && !clientId.trim().isEmpty()) {
                LOGGER.debug("Check that client_id is unique among all applications");
                final Set<Application> applications = applicationRepository.findAllByEnvironment(GraviteeContext.getCurrentEnvironment(), ApplicationStatus.ACTIVE);
                final Optional<Application> byClientId = applications.stream().filter(app -> app.getMetadata() != null && clientId.equals(app.getMetadata().get("client_id"))).findAny();
                if (byClientId.isPresent() && !byClientId.get().getId().equals(optApplicationToUpdate.get().getId())) {
                    LOGGER.error("An application already exists with the same client_id");
                    throw new ClientIdAlreadyExistsException(clientId);
                }
            }
        } else {
            // Check that client registration is enabled
            checkClientRegistrationEnabled();
            checkClientSettings(updateApplicationEntity.getSettings().getoAuthClient());
            // Update an OAuth client
            final String registrationPayload = optApplicationToUpdate.get().getMetadata().get("registration_payload");
            if (registrationPayload != null) {
                ClientRegistrationResponse registrationResponse = clientRegistrationService.update(registrationPayload, updateApplicationEntity);
                if (registrationResponse != null) {
                    try {
                        metadata.put("client_id", registrationResponse.getClientId());
                        metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        Application application = convert(updateApplicationEntity);
        application.setId(applicationId);
        application.setEnvironmentId(optApplicationToUpdate.get().getEnvironmentId());
        application.setStatus(ApplicationStatus.ACTIVE);
        application.setType(optApplicationToUpdate.get().getType());
        application.setCreatedAt(optApplicationToUpdate.get().getCreatedAt());
        application.setUpdatedAt(new Date());
        metadata.forEach((key, value) -> application.getMetadata().put(key, value));
        Application updatedApplication = applicationRepository.update(application);
        // Audit
        auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_UPDATED, updatedApplication.getUpdatedAt(), optApplicationToUpdate.get(), updatedApplication);
        // Set correct client_id for all subscriptions
        SubscriptionQuery subQuery = new SubscriptionQuery();
        subQuery.setApplication(applicationId);
        subQuery.setStatuses(Collections.singleton(SubscriptionStatus.ACCEPTED));
        subscriptionService.search(subQuery).forEach(new Consumer<SubscriptionEntity>() {

            @Override
            public void accept(SubscriptionEntity subscriptionEntity) {
                UpdateSubscriptionEntity updateSubscriptionEntity = new UpdateSubscriptionEntity();
                updateSubscriptionEntity.setId(subscriptionEntity.getId());
                updateSubscriptionEntity.setStartingAt(subscriptionEntity.getStartingAt());
                updateSubscriptionEntity.setEndingAt(subscriptionEntity.getEndingAt());
                subscriptionService.update(updateSubscriptionEntity, application.getMetadata().get("client_id"));
            }
        });
        return convert(Collections.singleton(updatedApplication)).iterator().next();
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to update application {}", applicationId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to update application %s", applicationId), ex);
    }
}
Also used : io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) AuditEvent(io.gravitee.repository.management.model.Application.AuditEvent) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ApplicationTypeService(io.gravitee.rest.api.service.configuration.application.ApplicationTypeService) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) HookScope(io.gravitee.rest.api.service.notification.HookScope) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) Collections.singletonList(java.util.Collections.singletonList) ClientRegistrationService(io.gravitee.rest.api.service.configuration.application.ClientRegistrationService) io.gravitee.rest.api.model(io.gravitee.rest.api.model) ApplicationRepository(io.gravitee.repository.management.api.ApplicationRepository) Collectors.toSet(java.util.stream.Collectors.toSet) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) ApplicationHook(io.gravitee.rest.api.service.notification.ApplicationHook) ApplicationSettings(io.gravitee.rest.api.model.application.ApplicationSettings) OAuthClientSettings(io.gravitee.rest.api.model.application.OAuthClientSettings) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) UuidString(io.gravitee.rest.api.service.common.UuidString) Logger(org.slf4j.Logger) Collections.emptySet(java.util.Collections.emptySet) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) ApplicationTypeEntity(io.gravitee.rest.api.model.configuration.application.ApplicationTypeEntity) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ClientRegistrationResponse(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) Key(io.gravitee.rest.api.model.parameters.Key) Consumer(java.util.function.Consumer) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) Collectors.toList(java.util.stream.Collectors.toList) ApplicationCriteria(io.gravitee.repository.management.api.search.ApplicationCriteria) GenericNotificationConfigEntity(io.gravitee.rest.api.model.notification.GenericNotificationConfigEntity) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery) NotNull(org.jetbrains.annotations.NotNull) DatatypeConverter(javax.xml.bind.DatatypeConverter) ClientRegistrationProviderEntity(io.gravitee.rest.api.model.configuration.application.registration.ClientRegistrationProviderEntity) SystemRole(io.gravitee.rest.api.model.permissions.SystemRole) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ClientRegistrationResponse(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse) UuidString(io.gravitee.rest.api.service.common.UuidString) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 5 with ClientRegistrationResponse

use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.

the class ClientRegistrationServiceImpl method update.

@Override
public ClientRegistrationResponse update(String previousRegistrationResponse, UpdateApplicationEntity application) {
    try {
        ClientRegistrationResponse registrationResponse = mapper.readValue(previousRegistrationResponse, ClientRegistrationResponse.class);
        if (registrationResponse.getRegistrationAccessToken() == null || registrationResponse.getRegistrationAccessToken().isEmpty() || registrationResponse.getRegistrationClientUri() == null || registrationResponse.getRegistrationClientUri().isEmpty()) {
            throw new RegisteredClientNotUpdatableException();
        }
        // Update an OAuth client
        Set<ClientRegistrationProviderEntity> providers = findAll();
        if (providers == null || providers.isEmpty()) {
            throw new MissingDynamicClientRegistrationProviderException();
        }
        // For now, took the first provider
        ClientRegistrationProviderEntity provider = providers.iterator().next();
        // Get provider client
        DynamicClientRegistrationProviderClient registrationProviderClient = getDCRClient(false, provider);
        ClientRegistrationRequest registrationRequest = mapper.readValue(previousRegistrationResponse, ClientRegistrationRequest.class);
        registrationRequest.setSoftwareId(provider.getSoftwareId());
        return registrationProviderClient.update(registrationResponse.getRegistrationAccessToken(), registrationResponse.getRegistrationClientUri(), convert(registrationRequest, application), application.getSettings().getoAuthClient().getClientId());
    } catch (Exception ex) {
        LOGGER.error("Unexpected error while updating a client", ex);
        return null;
    }
}
Also used : ClientRegistrationResponse(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse) NewClientRegistrationProviderEntity(io.gravitee.rest.api.model.configuration.application.registration.NewClientRegistrationProviderEntity) UpdateClientRegistrationProviderEntity(io.gravitee.rest.api.model.configuration.application.registration.UpdateClientRegistrationProviderEntity) ClientRegistrationProviderEntity(io.gravitee.rest.api.model.configuration.application.registration.ClientRegistrationProviderEntity) ClientRegistrationRequest(io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationRequest) DynamicClientRegistrationProviderClient(io.gravitee.rest.api.service.impl.configuration.application.registration.client.DynamicClientRegistrationProviderClient) DiscoveryBasedDynamicClientRegistrationProviderClient(io.gravitee.rest.api.service.impl.configuration.application.registration.client.DiscoveryBasedDynamicClientRegistrationProviderClient) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) IOException(java.io.IOException)

Aggregations

ClientRegistrationResponse (io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse)6 UuidString (io.gravitee.rest.api.service.common.UuidString)5 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 ClientRegistrationProviderEntity (io.gravitee.rest.api.model.configuration.application.registration.ClientRegistrationProviderEntity)4 IOException (java.io.IOException)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ApplicationSettings (io.gravitee.rest.api.model.application.ApplicationSettings)2 OAuthClientSettings (io.gravitee.rest.api.model.application.OAuthClientSettings)2 SimpleApplicationSettings (io.gravitee.rest.api.model.application.SimpleApplicationSettings)2 NewClientRegistrationProviderEntity (io.gravitee.rest.api.model.configuration.application.registration.NewClientRegistrationProviderEntity)2 UpdateClientRegistrationProviderEntity (io.gravitee.rest.api.model.configuration.application.registration.UpdateClientRegistrationProviderEntity)2 DiscoveryBasedDynamicClientRegistrationProviderClient (io.gravitee.rest.api.service.impl.configuration.application.registration.client.DiscoveryBasedDynamicClientRegistrationProviderClient)2 DynamicClientRegistrationProviderClient (io.gravitee.rest.api.service.impl.configuration.application.registration.client.DynamicClientRegistrationProviderClient)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Page (io.gravitee.common.data.domain.Page)1 TemplateEngine (io.gravitee.el.TemplateEngine)1 ApplicationRepository (io.gravitee.repository.management.api.ApplicationRepository)1 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)1 ApplicationCriteria (io.gravitee.repository.management.api.search.ApplicationCriteria)1 io.gravitee.repository.management.model (io.gravitee.repository.management.model)1