aws / aws-msk-iam-auth

Enables developers to use AWS Identity and Access Management (IAM) to connect to their Amazon Managed Streaming for Apache Kafka (Amazon MSK) clusters.
Apache License 2.0
137 stars 65 forks source link

How to set java system property of AKSK porperly with springboot #100

Open xpdable opened 1 year ago

xpdable commented 1 year ago

I used to set env before my spingboot starts, and everything is fine. Now I need to decrypt AKSK when the application starts, therefore I tried to set java system property in the event listener as below, but it seems does not work for the kafka client. Does anyone have any sample of working with springboot?

public class AfterConfigListener implements SmartApplicationListener, Ordered {

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return (ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(aClass)) ||
                ApplicationPreparedEvent.class.isAssignableFrom(aClass) ||
                ApplicationStartingEvent.class.isAssignableFrom(aClass);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ApplicationStartingEvent){
            System.setProperty("aws.accessKeyId","asfd");
            System.setProperty("aws.secretAccessKey","asdf/abcdefg");
        }
    }

    @Override
    public int getOrder(){
        return(ConfigFileApplicationListener.DEFAULT_ORDER + 1);
    }

}

application.yml:

spring:
  application:
    name: aws-msk-producer-demo
  kafka:
    listener:
      type: batch
    producer:
      ...
    properties:
      security.protocol: SASL_SSL
      sasl:
        mechanism: AWS_MSK_IAM
        jaas.config: software.amazon.msk.auth.iam.IAMLoginModule required;
        client.callback.handler.class: software.amazon.msk.auth.iam.IAMClientCallbackHandler

build.gradle:

plugins {
    id 'org.springframework.boot' version '2.7.2'
    id 'io.spring.dependency-management' version '1.0.12.RELEASE'
    id 'java'
}

version = '0.0.1'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.kafka:spring-kafka'
    implementation group: 'org.apache.kafka', name: 'kafka-clients', version: '3.2.0'
    implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.3'
    implementation group: 'software.amazon.msk', name: 'aws-msk-iam-auth', version: '1.1.4'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.kafka:spring-kafka-test'
}
serhiikartashov commented 6 months ago

+1