Andrew Treacy
Andrew Treacy

Reputation: 3

AWSSDK for Swift / supplying credentials at runtime

I am trying to list files in an S3 bucket and eventually upload and do more with the new AWSSDK.

I have successfully gotten the sample code BELOW to work, and more, to list out objects (filenames) in an S3 bucket with the code below: However when i run the code outside the XCode IDE environment I understand I have to supply credentials, as XCode consumes the AWS keys from the local ENVIRONMENT VARIABLES I setup.

I want to manually pas sin the credentials/keys to the client object at runtime BUT cannot find ANYWHERE how to configure the AWSClient object to include the credential keys (ACCESS & SECRET).

ANY help would be greatly appreciated as I cannot find anywhere the examples of how to do this, despite the documentation saying you can manually provide them to AWSClient object.

dev code that works in IDE environment is ...

import Foundation       // standard apple foundation libraries
import ClientRuntime    // low level awssdk suport features
import AWSS3            // S3 module

  func listBucketFiles(bucket: String) async throws -> [String] {
        
        // Get an S3Client with which to access Amazon S3.
        let client = try S3Client(region: "us-east-1")
        
        let input = ListObjectsV2Input(
            bucket: bucket
        )
        let output = try await client.listObjectsV2(input: input)
        var names: [String] = []
        
        guard let objList = output.contents else {
            return []
        }
        
        for obj in objList {
            if let objName = obj.key {
                names.append(objName)
            }
        }
        
        self.bucketNames = names
        
        return names
    }

see example above, the code worsks thru Xcode but in production does not authenticate

Upvotes: 0

Views: 550

Answers (1)

emeraldsanto
emeraldsanto

Reputation: 4731

You can initialize an instance of S3Client.S3Configuration, which lets you specify credentials manually. instead of relying on the default source mechanisms (environment variables, EC2 instance profile, etc.).

let credentials = AWSCredentialsProviderStaticConfig(
    accessKey: "REPLACE_THIS",
    secret: "REPLACE_THIS"
)

let config = try await S3Client.S3ClientConfiguration(
  credentialsProvider: AWSCredentialsProvider.fromStatic(credentials),
  region: "us-east-1", 
)

let client = try S3Client(config: config)

However, if you're building a client application, please don't embed AWS credentials as they can be easily accessed by your end users. Instead, move the AWS logic to a server and communicate with it from your app using an HTTP API.

Upvotes: 0

Related Questions