Issue with passwordless Authentication with AWS IAM

Hi Folks.

Currnetly, i’am working on the project using aws batch to access MongoDB to query the data.

Since both instances are under the same aws account, we decided to authenticate with iam.

However, Authenticate keep failing even after i pass accessKey and secretKey. (IAM role is added to mongodbside) and below is my code.

        val credentialsProvider = DefaultCredentialsProvider.create().resolveCredentials()

        val accessKey = URLEncoder.encode(credentialsProvider.accessKeyId(), StandardCharsets.UTF_8.toString())
        val secretKey = URLEncoder.encode(credentialsProvider.secretAccessKey(), StandardCharsets.UTF_8.toString())

        val connectionString =
            "mongodb+srv://$accessKey:$secretKey@<uri>/" +
                    "?authSource=%24external&authMechanism=MONGODB-AWS" +

        val serverApi = ServerApi.builder()

        val mongoClientSettings = MongoClientSettings.builder()

        MongoClient.create(mongoClientSettings).use {
            val database = it.getDatabase("admin")

Can anyone help with this?