Skip to content

Commit 2c66500

Browse files
committed
Commit abstracted AuthTokenGenerator
1 parent bbc53a5 commit 2c66500

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
package aws.sdk.kotlin.runtime.auth
6+
7+
import aws.sdk.kotlin.runtime.auth.credentials.DefaultChainCredentialsProvider
8+
import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials
9+
import aws.smithy.kotlin.runtime.auth.awssigning.AwsSignatureType
10+
import aws.smithy.kotlin.runtime.auth.awssigning.AwsSigningConfig
11+
import aws.smithy.kotlin.runtime.auth.awssigning.AwsSigningConfig.Companion.invoke
12+
import aws.smithy.kotlin.runtime.auth.awssigning.DefaultAwsSigner
13+
import aws.smithy.kotlin.runtime.http.HttpMethod
14+
import aws.smithy.kotlin.runtime.http.request.HttpRequest
15+
import aws.smithy.kotlin.runtime.net.url.Url
16+
import aws.smithy.kotlin.runtime.time.Clock
17+
import kotlinx.coroutines.runBlocking
18+
import kotlin.time.Duration
19+
20+
/**
21+
* Generates an authentication token, which is a SigV4-signed URL with the HTTP scheme removed.
22+
* @param service The name of the service the token is being generated for
23+
* @param credentials The credentials to use when generating the auth token, defaults to resolving credentials from the [DefaultChainCredentialsProvider]
24+
*/
25+
public class AuthTokenGenerator(
26+
public val service: String,
27+
public val credentials: Credentials? = runBlocking { DefaultChainCredentialsProvider().resolve() },
28+
) {
29+
private fun String.trimScheme() = removePrefix("http://").removePrefix("https://")
30+
31+
public suspend fun generateAuthToken(endpoint: Url, region: String, expiration: Duration): String {
32+
val req = HttpRequest(HttpMethod.GET, endpoint)
33+
34+
val creds = credentials
35+
val serv = service
36+
37+
val config = AwsSigningConfig {
38+
credentials = creds
39+
this.region = region
40+
service = serv
41+
signingDate = Clock.System.now()
42+
expiresAfter = expiration
43+
signatureType = AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS
44+
}
45+
46+
return DefaultAwsSigner.sign(req, config).output.url.toString().trimScheme()
47+
}
48+
}

0 commit comments

Comments
 (0)