Skip to content

Commit 0474838

Browse files
authored
chore(auth): Add typesafe classes for handling auth tokens (#3123)
1 parent 288a082 commit 0474838

25 files changed

+325
-317
lines changed

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/AWSCognitoAuthSession.kt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ internal fun AmplifyCredential.getCognitoSession(
9999
}
100100

101101
return try {
102-
AuthSessionResult.success(userPoolTokens?.accessToken?.let(SessionHelper::getUserSub))
102+
AuthSessionResult.success(userPoolTokens?.accessToken?.userSub)
103103
} catch (e: Exception) {
104104
AuthSessionResult.failure(UnknownException(cause = e))
105105
}
@@ -115,9 +115,9 @@ internal fun AmplifyCredential.getCognitoSession(
115115

116116
return AuthSessionResult.success(
117117
AWSCognitoUserPoolTokens(
118-
accessToken = cognitoUserPoolTokens.accessToken,
119-
idToken = cognitoUserPoolTokens.idToken,
120-
refreshToken = cognitoUserPoolTokens.refreshToken
118+
accessToken = cognitoUserPoolTokens.accessToken?.tokenValue,
119+
idToken = cognitoUserPoolTokens.idToken?.tokenValue,
120+
refreshToken = cognitoUserPoolTokens.refreshToken?.tokenValue
121121
)
122122
)
123123
}

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/actions/FetchAuthSessionCognitoActions.kt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import aws.sdk.kotlin.services.cognitoidentity.model.GetIdRequest
2020
import aws.sdk.kotlin.services.cognitoidentityprovider.getTokensFromRefreshToken
2121
import aws.smithy.kotlin.runtime.time.Instant
2222
import com.amplifyframework.auth.cognito.AuthEnvironment
23-
import com.amplifyframework.auth.cognito.helpers.SessionHelper
2423
import com.amplifyframework.auth.exceptions.NotAuthorizedException
2524
import com.amplifyframework.auth.exceptions.SessionExpiredException
2625
import com.amplifyframework.auth.exceptions.SignedOutException
@@ -48,7 +47,7 @@ internal object FetchAuthSessionCognitoActions : FetchAuthSessionActions {
4847
val deviceMetadata: DeviceMetadata.Metadata? = getDeviceMetadata(username)
4948

5049
val response = cognitoAuthService.cognitoIdentityProviderClient?.getTokensFromRefreshToken {
51-
refreshToken = tokens.refreshToken
50+
refreshToken = tokens.refreshToken?.tokenValue
5251
clientId = configuration.userPool?.appClient
5352
clientSecret = configuration.userPool?.appClientSecret
5453
deviceKey = deviceMetadata?.deviceKey
@@ -58,13 +57,13 @@ internal object FetchAuthSessionCognitoActions : FetchAuthSessionActions {
5857
val refreshedUserPoolTokens = CognitoUserPoolTokens(
5958
idToken = response?.authenticationResult?.idToken,
6059
accessToken = response?.authenticationResult?.accessToken,
61-
refreshToken = response?.authenticationResult?.refreshToken ?: tokens.refreshToken,
60+
refreshToken = response?.authenticationResult?.refreshToken ?: tokens.refreshToken?.tokenValue,
6261
expiration = Instant.now().plus(expiresIn.seconds).epochSeconds
6362
)
6463

6564
val updatedSignedInData = signedInData.copy(
66-
userId = refreshedUserPoolTokens.accessToken?.let(SessionHelper::getUserSub) ?: signedInData.userId,
67-
username = refreshedUserPoolTokens.accessToken?.let(SessionHelper::getUsername) ?: username,
65+
userId = refreshedUserPoolTokens.accessToken?.userSub ?: signedInData.userId,
66+
username = refreshedUserPoolTokens.accessToken?.username ?: username,
6867
cognitoUserPoolTokens = refreshedUserPoolTokens
6968
)
7069

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/actions/HostedUICognitoActions.kt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ package com.amplifyframework.auth.cognito.actions
1717

1818
import com.amplifyframework.auth.cognito.AuthEnvironment
1919
import com.amplifyframework.auth.cognito.exceptions.configuration.InvalidOauthConfigurationException
20-
import com.amplifyframework.auth.cognito.helpers.JWTParser
2120
import com.amplifyframework.statemachine.Action
2221
import com.amplifyframework.statemachine.codegen.actions.HostedUIActions
2322
import com.amplifyframework.statemachine.codegen.data.DeviceMetadata
@@ -54,8 +53,8 @@ internal object HostedUICognitoActions : HostedUIActions {
5453
if (hostedUIClient == null) throw InvalidOauthConfigurationException()
5554

5655
val token = hostedUIClient.fetchToken(event.uri)
57-
val userId = token.accessToken?.let { JWTParser.getClaim(it, "sub") } ?: ""
58-
val username = token.accessToken?.let { JWTParser.getClaim(it, "username") } ?: ""
56+
val userId = token.accessToken?.userSub ?: ""
57+
val username = token.accessToken?.username ?: ""
5958

6059
val signedInData = SignedInData(
6160
userId,

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/actions/SignInCognitoActions.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ internal object SignInCognitoActions : SignInActions {
126126

127127
cognitoAuthService.cognitoIdentityProviderClient?.confirmDevice(
128128
ConfirmDeviceRequest.invoke {
129-
this.accessToken = event.signedInData.cognitoUserPoolTokens.accessToken
129+
this.accessToken = event.signedInData.cognitoUserPoolTokens.accessToken?.tokenValue
130130
this.deviceKey = deviceKey
131131
this.deviceName = Build.MODEL
132132
this.deviceSecretVerifierConfig = DeviceSecretVerifierConfigType.invoke {

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/actions/SignOutCognitoActions.kt

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import aws.sdk.kotlin.services.cognitoidentityprovider.model.GlobalSignOutReques
1919
import aws.sdk.kotlin.services.cognitoidentityprovider.model.RevokeTokenRequest
2020
import com.amplifyframework.auth.cognito.AuthEnvironment
2121
import com.amplifyframework.auth.cognito.exceptions.configuration.InvalidOauthConfigurationException
22-
import com.amplifyframework.auth.cognito.helpers.JWTParser
2322
import com.amplifyframework.statemachine.Action
2423
import com.amplifyframework.statemachine.codegen.actions.SignOutActions
2524
import com.amplifyframework.statemachine.codegen.data.DeviceMetadata
@@ -76,15 +75,15 @@ internal object SignOutCognitoActions : SignOutActions {
7675
val accessToken = event.signedInData.cognitoUserPoolTokens.accessToken
7776
val evt = try {
7877
cognitoAuthService.cognitoIdentityProviderClient?.globalSignOut(
79-
GlobalSignOutRequest { this.accessToken = accessToken }
78+
GlobalSignOutRequest { this.accessToken = accessToken?.tokenValue }
8079
)
8180
SignOutEvent(
8281
SignOutEvent.EventType.RevokeToken(event.signedInData, hostedUIErrorData = event.hostedUIErrorData)
8382
)
8483
} catch (e: Exception) {
8584
logger.warn("Failed to sign out globally.", e)
8685
val globalSignOutErrorData = GlobalSignOutErrorData(
87-
accessToken = accessToken,
86+
accessToken = accessToken?.tokenValue,
8887
error = e
8988
)
9089
SignOutEvent(
@@ -106,19 +105,19 @@ internal object SignOutCognitoActions : SignOutActions {
106105
val refreshToken = event.signedInData.cognitoUserPoolTokens.refreshToken
107106
val evt = try {
108107
// Check for "origin_jti" claim in access token, else skip revoking
109-
if (accessToken?.let { JWTParser.hasClaim(it, "origin_jti") } == true) {
108+
if (accessToken?.tokenRevocationId != null) {
110109
cognitoAuthService.cognitoIdentityProviderClient?.revokeToken(
111110
RevokeTokenRequest {
112111
clientId = configuration.userPool?.appClient
113112
clientSecret = configuration.userPool?.appClientSecret
114-
token = refreshToken
113+
token = refreshToken?.tokenValue
115114
}
116115
)
117116
SignOutEvent(SignOutEvent.EventType.SignOutLocally(event.signedInData, event.hostedUIErrorData))
118117
} else {
119118
logger.debug("Access Token does not contain `origin_jti` claim. Skip revoking tokens.")
120119
val error = RevokeTokenErrorData(
121-
refreshToken = refreshToken,
120+
refreshToken = refreshToken?.tokenValue,
122121
error = Exception("Access Token does not contain `origin_jti` claim. Skip revoking tokens.")
123122
)
124123

@@ -134,7 +133,7 @@ internal object SignOutCognitoActions : SignOutActions {
134133
} catch (e: Exception) {
135134
logger.warn("Failed to revoke tokens.", e)
136135
val error = RevokeTokenErrorData(
137-
refreshToken = refreshToken,
136+
refreshToken = refreshToken?.tokenValue,
138137
error = e
139138
)
140139

@@ -156,7 +155,7 @@ internal object SignOutCognitoActions : SignOutActions {
156155
logger.verbose("$id Starting execution")
157156

158157
val error = RevokeTokenErrorData(
159-
refreshToken = event.signedInData.cognitoUserPoolTokens.refreshToken,
158+
refreshToken = event.signedInData.cognitoUserPoolTokens.refreshToken?.tokenValue,
160159
error = Exception("RevokeToken not attempted because GlobalSignOut failed.")
161160
)
162161

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/data/AWSCognitoLegacyCredentialStore.kt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import android.content.Context
1919
import androidx.core.content.edit
2020
import com.amplifyframework.auth.AuthProvider
2121
import com.amplifyframework.auth.cognito.AuthConfiguration
22-
import com.amplifyframework.auth.cognito.helpers.SessionHelper
2322
import com.amplifyframework.auth.cognito.helpers.identityProviderName
2423
import com.amplifyframework.core.store.KeyValueRepository
2524
import com.amplifyframework.statemachine.codegen.data.AWSCredentials
@@ -216,13 +215,13 @@ internal class AWSCognitoLegacyCredentialStore(
216215
val signInMethod = retrieveUserPoolSignInMethod() ?: return null
217216
val tokenUserId =
218217
try {
219-
cognitoUserPoolTokens.accessToken?.let { SessionHelper.getUserSub(it) } ?: ""
218+
cognitoUserPoolTokens.accessToken?.userSub ?: ""
220219
} catch (e: Exception) {
221220
""
222221
}
223222
val tokenUsername =
224223
try {
225-
cognitoUserPoolTokens.accessToken?.let { SessionHelper.getUsername(it) } ?: ""
224+
cognitoUserPoolTokens.accessToken?.username ?: ""
226225
} catch (e: Exception) {
227226
""
228227
}

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/helpers/JWTParser.kt

Lines changed: 0 additions & 123 deletions
This file was deleted.

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/helpers/SessionHelper.kt

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -21,29 +21,6 @@ import java.time.Instant
2121
import java.time.temporal.ChronoUnit
2222

2323
internal object SessionHelper {
24-
/**
25-
* Returns expiration of this id token.
26-
* @return id token expiration claim as {@link java.time.Instant} in UTC.
27-
*/
28-
internal fun getExpiration(token: String): Instant? {
29-
val claim = JWTParser.getClaim(token, "exp")
30-
return claim?.let {
31-
Instant.ofEpochSecond(claim.toLong())
32-
}
33-
}
34-
35-
/**
36-
* Returns the username set in the access token.
37-
* @return Username.
38-
*/
39-
fun getUsername(token: String): String? = JWTParser.getClaim(token, "username")
40-
41-
/**
42-
* Returns the usersub set in the access token.
43-
* @return usersub
44-
*/
45-
fun getUserSub(token: String): String? = JWTParser.getClaim(token, "sub")
46-
4724
/**
4825
* Returns true if the access and id tokens have not expired.
4926
* @return boolean to indicate if the access and id tokens are expired.
@@ -53,10 +30,9 @@ internal object SessionHelper {
5330
return when {
5431
userPoolTokens.idToken == null -> false
5532
userPoolTokens.accessToken == null -> false
56-
else -> currentTimeStamp < getExpiration(userPoolTokens.idToken) &&
57-
currentTimeStamp < getExpiration(
58-
userPoolTokens.accessToken
59-
)
33+
else ->
34+
currentTimeStamp < userPoolTokens.idToken.expiration &&
35+
currentTimeStamp < userPoolTokens.accessToken.expiration
6036
}
6137
}
6238

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/helpers/SignInChallengeHelper.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,9 @@ internal object SignInChallengeHelper {
5959
): StateMachineEvent = when {
6060
authenticationResult != null -> {
6161
authenticationResult.let {
62-
val userId = it.accessToken?.let { token -> SessionHelper.getUserSub(token) } ?: ""
63-
val expiresIn = Instant.now().plus(it.expiresIn.seconds).epochSeconds
64-
val tokens = CognitoUserPoolTokens(it.idToken, it.accessToken, it.refreshToken, expiresIn)
62+
val expiration = Instant.now().plus(it.expiresIn.seconds).epochSeconds
63+
val tokens = CognitoUserPoolTokens(it.idToken, it.accessToken, it.refreshToken, expiration)
64+
val userId = tokens.accessToken?.userSub ?: ""
6565
val signedInData = SignedInData(
6666
userId,
6767
username,

0 commit comments

Comments
 (0)