Sping Boot RabbitMQ尝试验证未授权的类异常

tpgth1q7  于 2023-11-19  发布在  RabbitMQ
关注(0)|答案(2)|浏览(1508)

我在Sping Boot 项目中使用RabbitMQ:
第一个月

@Component
@AllArgsConstructor
public class UserSender {

    private final RabbitTemplate rabbitTemplate;

    public String send() {
        User user = new User(1L, "Tom", "123");
        rabbitTemplate.convertAndSend("userQueue", user);
        return "user sender sent: " + user;
    }
}

字符串
Receiver

@Component
public class UserReceiver {

    @RabbitListener(queues = "userQueue")
    @RabbitHandler
    private void process(User user) {
        System.out.println("received user: " + user);
    }
}


启动时出现异常:

Caused by: java.lang.SecurityException: Attempt to deserialize unauthorized class com.example.lab06.entity.User; add allowed class name patterns to the message converter or, if you trust the message orginiator, set environment variable 'SPRING_AMQP_DESERIALIZATION_TRUST_ALL' or system property 'spring.amqp.deserialization.trust.all' to true


我查了 Spring AMPQ文档
您可以在这些转换器上使用allowedListPatterns属性设置模式。或者,如果您信任所有消息发起者,则可以将环境变量SPRING_AMQP_DESERIALIZATION_TRUST_ALL或系统属性spring.amqp.deserialization.trust.all设置为true
但是,我不能在application.properties中设置spring.amqp.deserialization.trust.all。我得到这个错误:

Cannot resolve configuration property 'spring.amqp.deserialization.trust.all'


怎么修?

2nbm6dog

2nbm6dog1#

文件指出(强调我的):
.将环境变量SPRING_AMQP_DESERIALIZATION_TRUST_ALL系统属性spring.amqp.deserialization.trust.all设置为true
application.properties中配置的值是 not 环境变量或系统属性。环境变量在您的环境中设置,系统属性通常作为-D参数传递给JVM。
因此,您需要以适合您的用例的任何方式将spring.amqp.deserialization.trust.all设置为系统属性
值得注意的是,此设置实质上绕过了在验证消息时的安全检查,并可能使您的应用程序容易受到远程攻击。建议您使用转换器上的allowedListPatterns属性设置模式。

mnemlml8

mnemlml82#

谢谢@Bertram,这是我使用setTrustedPackages的解决方案:

@Configuration
public class RabbitMQConfig {

    @Bean
    public MessageConverter jsonToMapMessageConverter() {
        DefaultClassMapper defaultClassMapper = new DefaultClassMapper();
        defaultClassMapper.setTrustedPackages("YOUR_PACKAGE_NAME"); // trusted packages
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
        jackson2JsonMessageConverter.setClassMapper(defaultClassMapper);
        return jackson2JsonMessageConverter;
    }
    
    // ...
}

字符串

相关问题