The class is not in the trusted packages although appears in the list of trusted packages

HeyItsMe picture HeyItsMe · May 27, 2018 · Viewed 10.2k times · Source

I am trying to implement a simple Kafka communication between 2 different Spring Boot applications with out any special settings, this application has only one kafkalistener. My yml for the consumer is the following:

spring:
  kafka:
    bootstrap-servers: ip_here
    topic:
      json: topic_here
    consumer:
      group-id: group_id
      auto-offset-reset: earliest
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      properties:
        spring:
          json:
            trusted:
              packages: 'com.example.kw.dtos.Classdata'

The error I am receiving is the following:

Caused by: java.lang.IllegalArgumentException: The class 'com.example.kw.dtos.Classdata' is not in the trusted packages: [java.util, java.lang, com.example.kw.dtos.Classdata]. If you believe this class is safe to deserialize, please provide its name. If the serialization is only done by a trusted source, you can also enable trust all (*).

The package is in the trusted packages but something is wrong.

My factory class:

@Configuration
@EnableKafka
public class MsgListener {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "json");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.example.kw.dtos.Classdata");
        return props;
    }

    @Bean
    public ConsumerFactory<String, Classdata> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(
                consumerConfigs(),
                new StringDeserializer(),
                new JsonDeserializer<>(Classdata.class));
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, Classdata> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, Classdata> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }
}

Answer

Gary Russell picture Gary Russell · May 27, 2018

It should be just the package com.example.kw.dtos

String packageName = ClassUtils.getPackageName(requestedType).replaceFirst("\\[L", "");
for (String trustedPackage : this.trustedPackages) {
    if (packageName.equals(trustedPackage)) {
        return true;
    }
}