Search code examples
spring-bootxstreamaxon

ForbiddenClassException appears during handling Axon event?


I have sandbox application microservices based on SpringBoot, SpringData JPA, Axon. I created 2 simple microservices: orders service and products service and trying to explore Axon Sagas. During Saga transaction I execute order create command, when it happens Saga emits product reserve event. This event is handled in product service and it fails with:

Exception in thread "CommandProcessor-0" com.thoughtworks.xstream.security.ForbiddenClassException: com.udemy.shared.command.ReserveProductCommand

How it can be fixed?

controller code in orders microservice:

@PostMapping
    public String createOrder(@Valid @RequestBody OrderDTO order) {
        CreateOrderCommand createOrderCommand = CreateOrderCommand.builder()
                .orderId(UUID.randomUUID().toString())
                .userId("27b95829-4f3f-4ddf-8983-151ba010e35b")
                .productId(order.getProductId())
                .quantity(order.getQuantity())
                .addressId(order.getAddressId())
                .orderStatus(OrderStatus.CREATED)
                .build();
        return commandGateway.sendAndWait(createOrderCommand);
    }

commands code:

@Builder
@Data
public class CreateOrderCommand {
    @AggregateIdentifier
    private final String orderId;
    private final String userId;
    private final String productId;
    private final int quantity;
    private String addressId;
    private final OrderStatus orderStatus;
}

@Data
@Builder
public class ReserveProductCommand {
    @AggregateIdentifier
    private String productId;
    private String orderId;
    private String userId;
    private int quantity;
}

saga code:

@Slf4j
@Saga
public class OrdersSaga {
    @Autowired
    private transient CommandGateway commandGateway;

    @StartSaga
    @SagaEventHandler(associationProperty = "orderId")
    public void handle(OrderCreatedEvent event) {
        ReserveProductCommand reserveProductCommand = ReserveProductCommand.builder()
                .orderId(event.getOrderId())
                .productId(event.getProductId())
                .userId(event.getUserId())
                .quantity(event.getQuantity())
                .build();
        commandGateway.send(reserveProductCommand, (commandMessage, commandResultMessage) -> {
            if (commandResultMessage.isExceptional()) {
                log.error("Something went wrong during product reserve: " + commandResultMessage.exceptionResult().getMessage() );
            }
        });
        log.info("Created order command fired! Order id = " + event.getOrderId());
    }

    @SagaEventHandler(associationProperty = "orderId")
    public void handle(ProductReservedEvent event) {
        log.info("Handling product reserve event for product with id = " + event.getProductId());

    }
}

handler where occurs error(products microservice):

@Slf4j
@Component
public class ProductEventHandler {
    ProductsRepository repository;

    @EventHandler
    public void on(ProductReservedEvent event) {
        ProductEntity updatedProduct = repository.findByProductId(event.getProductId());
        updatedProduct.setQuantity(event.getQuantity());
        log.info("Product reserved event was applied in event handler for product with id - " + event.getProductId());
        repository.save(updatedProduct);
    }
}

After googling I found out, that different Spring Boot version can have different xstream version and more relevant xstream produces this exception. I downgraded Spring Boot version in these services to 2.7.8, but this didnt help

my project's JDK and structure can be seen on screens

enter image description here

enter image description here


Solution

  • Thanx to @Steven recommendations, I googled and found the solution. It's not very good, but as temporary solution it helps and can be updated according to concrete purposes. So basing on axon forum and this thread, in commonly used module I created Xstream config like:

    @Configuration
    public class AxonXstreamConfig {
    
        @Bean
        public XStream xStream() {
            XStream xStream = new XStream();
            xStream.addPermission(AnyTypePermission.ANY);
    
            return xStream;
        }
    }
    

    After that I imported it to to necessary service, for example:

    @EnableDiscoveryClient
    @SpringBootApplication
    @Import({ AxonXstreamConfig.class })
    public class ProductsApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ProductsApplication.class, args);
        }
    }
    

    Now I dont get that exception, but we must take in consideration, that this line:

    xStream.addPermission(AnyTypePermission.ANY);
    

    switches off any xstream serialization security, so for real-life working examples this is a bad practice and I did it because I'm just playing in sandbox and I'm concentrated on Axon learning and don't want waste much time on other things, but on those link can be found different examples of xstream config, which will allow to make proper config.