Skip to content

Commit e30b6d4

Browse files
authored
Add an example showing how to resolve credentials using SSO (Identity Center) (#6995)
1 parent 076371b commit e30b6d4

File tree

4 files changed

+175
-0
lines changed

4 files changed

+175
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// swift-tools-version:5.9
2+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
// SPDX-License-Identifier: Apache-2.0
4+
//
5+
// The swift-tools-version declares the minimum version of Swift required to
6+
// build this package.
7+
8+
import PackageDescription
9+
10+
let package = Package(
11+
name: "sso-resolver",
12+
// Let Xcode know the minimum Apple platforms supported.
13+
platforms: [
14+
.macOS(.v11),
15+
.iOS(.v13)
16+
],
17+
dependencies: [
18+
// Dependencies declare other packages that this package depends on.
19+
.package(
20+
url: "https://github.com/awslabs/aws-sdk-swift",
21+
from: "1.0.0"
22+
),
23+
.package(
24+
url: "https://github.com/apple/swift-argument-parser.git",
25+
branch: "main"
26+
),
27+
],
28+
targets: [
29+
// Targets are the basic building blocks of a package, defining a module or a test suite.
30+
// Targets can depend on other targets in this package and products from dependencies.
31+
.executableTarget(
32+
name: "sso-resolver",
33+
dependencies: [
34+
.product(name: "AWSSTS", package: "aws-sdk-swift"),
35+
.product(name: "AWSS3", package: "aws-sdk-swift"),
36+
.product(name: "ArgumentParser", package: "swift-argument-parser"),
37+
],
38+
path: "Sources"),
39+
]
40+
)
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
//
4+
/// A simple example that shows how to use the AWS SDK for Swift to
5+
/// authenticate using SSO credentials from AWS Identity Center.
6+
7+
// snippet-start:[swift.identity.sso.imports]
8+
import ArgumentParser
9+
import AWSS3
10+
import AWSSDKIdentity
11+
import AWSSTS
12+
import Foundation
13+
import SmithyIdentity
14+
// snippet-end:[swift.identity.sso.imports]
15+
16+
struct ExampleCommand: ParsableCommand {
17+
@Option(help: "AWS profile name (default: 'default')")
18+
var profile: String? = nil
19+
@Option(help: "AWS configuration file path (default: '~/.aws/config')")
20+
var config: String? = nil
21+
@Option(help: "AWS credentials file path (default: '~/.aws/credentials')")
22+
var credentials: String? = nil
23+
24+
static var configuration = CommandConfiguration(
25+
commandName: "sso-resolver",
26+
abstract: """
27+
Demonstrates how to use an SSO credential identity resolver with the
28+
AWS SDK for Swift.
29+
""",
30+
discussion: """
31+
"""
32+
)
33+
34+
/// Called by ``main()`` to do the actual running of the AWS
35+
/// example.
36+
func runAsync() async throws {
37+
do {
38+
// snippet-start: [swift.identity.sso.create-resolver]
39+
let identityResolver = try SSOAWSCredentialIdentityResolver(
40+
profileName: profile,
41+
configFilePath: config,
42+
credentialsFilePath: credentials
43+
)
44+
// snippet-end: [swift.identity.sso.create-resolver]
45+
46+
// Call the function that fetches the Amazon S3 bucket names, then
47+
// output the names.
48+
49+
let names = try await getBucketNames(identityResolver: identityResolver)
50+
51+
print("Found \(names.count) buckets:")
52+
for name in names {
53+
print(" \(name)")
54+
}
55+
} catch {
56+
print("ERROR: Error getting bucket names in runAsync:", dump(error))
57+
throw error
58+
}
59+
}
60+
}
61+
62+
/// Return an array containing the names of all available buckets using
63+
/// the specified credential identity resolver to authenticate.
64+
///
65+
/// - Parameter identityResolver: Any type of `AWSCredentialIdentityResolver`,
66+
/// used to authenticate and authorize the user for access to the bucket
67+
/// names.
68+
///
69+
/// - Throws: Re-throws errors from `ListBucketsPaginated`.
70+
///
71+
/// - Returns: An array of strings listing the buckets.
72+
func getBucketNames(identityResolver: (any AWSCredentialIdentityResolver)?)
73+
async throws -> [String] {
74+
do {
75+
// snippet-start:[swift.identity.sso.use-resolver]
76+
// Get an S3Client with which to access Amazon S3.
77+
let configuration = try await S3Client.S3ClientConfiguration(
78+
awsCredentialIdentityResolver: identityResolver
79+
)
80+
let client = S3Client(config: configuration)
81+
82+
// Use "Paginated" to get all the buckets. This lets the SDK handle
83+
// the 'continuationToken' in "ListBucketsOutput".
84+
let pages = client.listBucketsPaginated(
85+
input: ListBucketsInput(maxBuckets: 10)
86+
)
87+
// snippet-end:[swift.identity.sso.use-resolver]
88+
89+
// Get the bucket names.
90+
var bucketNames: [String] = []
91+
92+
do {
93+
for try await page in pages {
94+
guard let buckets = page.buckets else {
95+
// For this example, if the bucket list reference for the
96+
// page is `nil`, print an error and continue on with the
97+
// next page.
98+
print("ERROR: page is empty.")
99+
continue
100+
}
101+
102+
// Add the page's bucket names to the list.
103+
for bucket in buckets {
104+
bucketNames.append(bucket.name ?? "<unknown>")
105+
}
106+
}
107+
108+
return bucketNames
109+
} catch {
110+
throw error
111+
}
112+
}
113+
}
114+
115+
/// The program's asynchronous entry point.
116+
@main
117+
struct Main {
118+
/// The function that serves as the main asynchronous entry point for the
119+
/// example. It parses the command line using the Swift Argument Parser,
120+
/// then calls the `runAsync()` function to run the example itself.
121+
static func main() async {
122+
let args = Array(CommandLine.arguments.dropFirst())
123+
124+
do {
125+
let command = try ExampleCommand.parse(args)
126+
try await command.runAsync()
127+
} catch {
128+
ExampleCommand.exit(withError: error)
129+
}
130+
}
131+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#!/bin/bash
2+
echo "No automated tests available."
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#!/bin/bash
2+
echo "No automated tests available."

0 commit comments

Comments
 (0)