Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting logged out of Amplify when providing Credentials to SNSClient and restarting application #3225

Closed
brianmwadime opened this issue Sep 16, 2023 · 6 comments
Assignees
Labels
auth Issues related to the Auth category question General question

Comments

@brianmwadime
Copy link

brianmwadime commented Sep 16, 2023

Describe the bug

We are attempting to use the SNSClient in the aws-sdk-swift to work with SNS in our app.
We provide a configuration for an authenticated user's credentials via custom AWSCognitoCredentialsProviderHelper and AWSIdentityProviderManager -> AWSCognitoCredentialsProvider-> AWSServiceConfiguration then creating the client via AWSSNS.register(with: configuration!, forKey: "USEast2SNS")

But whenever the client is used it seems to clear or invalidate the Amplify logged in user with the message that we the user has to sign in again.

How can we not break the amplify credentials refreshing mechanism while still using the underlying aws-sdk-swift with authenticated credentials from Amplify.Auth.fetchAuthSession()

Steps To Reproduce

Provide a configuration for an authenticated user's credentials via custom AWSCognitoCredentialsProviderHelper or AWSIdentityProviderManager -> AWSCognitoCredentialsProvider-> AWSServiceConfiguration then creating the client via AWSSNS.register(with: configuration!, forKey: "USEast2SNS").

We are using the Amplify.Auth.fetchAuthSession() to provide the credentials for the custom identity provider. See below

class OIDCProvider: NSObject, AWSIdentityProviderManager {
	private var store = Set<AnyCancellable>()

	func logins() -> AWSTask<NSDictionary> {
		let completion = AWSTaskCompletionSource<NSString>()
		getToken(tokenCompletion: completion)
		return completion.task.continueOnSuccessWith { (task) -> AWSTask<NSDictionary>? in
			/// - NOTE: You can get the provider name/issuer by getting the JWT token issuer
			return AWSTask(result: ["cognito-idp.\(KEYS.region).amazonaws.com/\(KEYS.userPoolId)": task.result!])
		} as! AWSTask<NSDictionary>
		
	}
	
	func getToken(tokenCompletion: AWSTaskCompletionSource<NSString>) -> Void {
		Amplify.Publisher.create {
			try await Amplify.Auth.fetchAuthSession()
		}.sink {
			if case let .failure(authError) = $0 {
				tokenCompletion.set(error: authError)
			}
		}
		receiveValue: { session in
			if let cognitoTokenResult = (session as? AWSAuthCognitoSession)?.getCognitoTokens() {
				switch cognitoTokenResult {
				case .success(let tokens):
					tokenCompletion.set(result: tokens.idToken as NSString)
				case .failure(let error):
					tokenCompletion.set(error: error)
				}
			}
		}
		.store(in: &store)
	}

}

Expected behavior

A user's credentials should refresh upon expiry and the user should remain logged in.

Amplify Framework Version

2.16.0

Amplify Categories

API, Auth

Dependency manager

Swift PM

Swift version

5.8.1

CLI version

12.1.1

Xcode version

14.3.1 (14E300c)

Relevant log output

<details>
<summary>Log Messages</summary>


INSERT LOG MESSAGES HERE
```

Is this a regression?

No

Regression additional context

No response

Platforms

iOS

OS Version

iOS 16

Device

iPhone 8

Specific to simulators

No response

Additional context

No response

@sebaland sebaland added auth Issues related to the Auth category question General question labels Sep 18, 2023
@atierian
Copy link
Member

Thanks for opening this @brianmwadime.

You mentioned that you are using the aws-sdk-swift.

We are attempting to use the SNSClient in the aws-sdk-swift to work with SNS in our app.

But from the code examples, it appears that you're using AWS SDK iOS. Can you confirm which one your using please?

Thanks!

@brianmwadime
Copy link
Author

@atierian sorry for the mixup,
Added AWSSNS from the AWS SDK iOS via cocoapods.

@atierian
Copy link
Member

Thanks for the update.

Can you please enable verbose logging for Amplify and AWS SDK iOS, then post the logs after reproducing the issue. That will help us investigate this.

Amplify Swift

Amplify.Logging.logLevel = .verbose

AWS SDK iOS

// swift
AWSDDLog.sharedInstance.logLevel = .verbose

// objc
[AWSDDLog sharedInstance].logLevel = AWSDDLogLevelVerbose;

@atierian atierian self-assigned this Sep 18, 2023
@brianmwadime
Copy link
Author

brianmwadime commented Sep 19, 2023

@atierian after loging in via amplify and setting up the credentials for the AWSSNS client from AWS SDK iOS. I am able to use it to publish a message successfully. Then I rebuild and deploy from XCode and this is what's logged as all the amplify request fail with a message requesting the user to be signed in again.

2023-09-19 12:48:51.389842+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] Credential Store state change:

notConfigured
2023-09-19 12:48:51.389851+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.notConfigured" =     {
    };
}
2023-09-19 12:48:51.392747+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configuringAuth" =     {
    };
}
2023-09-19 12:48:51.394439+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/InitializeAuthConfiguration.swift Starting execution
2023-09-19 12:48:51.395614+0300 DesklessWorkers[1940:505585] [AuthenticationAWSCognitoAuthPlugin] Credential Store state change:

migratingLegacyStore
2023-09-19 12:48:51.396170+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/MigrateLegacyCredentialStore.swift Starting execution
2023-09-19 12:48:51.398361+0300 DesklessWorkers[1940:505266] [API<AWSAPIPlugin.AWSAPIPlugin: 0x283e60cc0>] Configure finished
2023-09-19 12:48:51.401692+0300 DesklessWorkers[1940:505266] [Amplify] No plugin found for configuration key `awsS3StoragePlugin`. Add a plugin for that key.
2023-09-19 12:48:51:417 DesklessWorkers[1940:505565] Retrieving credentials from keychain
2023-09-19 12:48:51.433085+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/MigrateLegacyCredentialStore.swift Guest user
2023-09-19 12:48:51.440543+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/MigrateLegacyCredentialStore.swift Sending event CredentialStoreEvent.loadCredentialStore
2023-09-19 12:48:51.440728+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Credential Store state change:

loadingStoredCredentials
2023-09-19 12:48:51.440764+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/LoadCredentialStore.swift Starting execution
2023-09-19 12:48:51.442532+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/LoadCredentialStore.swift Retreiving credential amplifyCredentials
2023-09-19 12:48:51.449063+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/LoadCredentialStore.swift Sending event CredentialStoreEvent.completedOperation
2023-09-19 12:48:51.449350+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/IdleCredentialStore.swift Starting execution
2023-09-19 12:48:51.449416+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/IdleCredentialStore.swift Sending event CredentialStoreEvent.moveToIdleState
2023-09-19 12:48:51.449442+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/InitializeAuthConfiguration.swift Sending event AuthEvent.validateCredentialAndConfiguration
2023-09-19 12:48:51.449703+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ValidateCredentialsAndConfiguration.swift Starting execution
2023-09-19 12:48:51.449907+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ValidateCredentialsAndConfiguration.swift Sending event AuthEvent.configureAuthentication
2023-09-19 12:48:51.450023+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.validatingCredentialsAndConfiguration" =     {
    };
}
2023-09-19 12:48:51.451339+0300 DesklessWorkers[1940:505564] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.notConfigured" =         {
        };
    };
}
2023-09-19 12:48:51.451885+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Credential Store state change:

success(AWSCognitoAuthPlugin.CredentialStoreData.amplifyCredentials(identityPoolOnly))
2023-09-19 12:48:51.451919+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/InitializeAuthenticationConfiguration.swift Starting execution
2023-09-19 12:48:51.451948+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Credential Store state change:

idle
2023-09-19 12:48:51.451968+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/InitializeAuthenticationConfiguration.swift Sending event AuthenticationEvent.configure
2023-09-19 12:48:51.452691+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ConfigureAuthentication.swift Start execution
2023-09-19 12:48:51.452718+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.configured" =         {
        };
    };
}
2023-09-19 12:48:51.453135+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ConfigureAuthentication.swift Sending event AuthenticationEvent.initializedSignedOut
2023-09-19 12:48:51.453279+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
    };
}
2023-09-19 12:48:51.453329+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ConfigureAuthentication.swift Sending event AuthEvent.authenticationConfigured
2023-09-19 12:48:51.454351+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/InitializeAuthorizationConfiguration.swift Starting execution
2023-09-19 12:48:51.454431+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/InitializeAuthorizationConfiguration.swift Sending event AuthorizationEvent.cachedCredentialsAvailable
2023-09-19 12:48:51.454767+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configuringAuthorization" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.notConfigured" =         {
        };
    };
}
2023-09-19 12:48:51.458997+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ConfigureAuthorization.swift Starting execution
2023-09-19 12:48:51.459046+0300 DesklessWorkers[1940:505624] [AuthenticationAWSCognitoAuthPlugin] AWSCognitoAuthPlugin/ConfigureAuthorization.swift Sending event AuthEvent.authorizationConfigured
2023-09-19 12:48:51.459123+0300 DesklessWorkers[1940:505565] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configuringAuthorization" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.sessionEstablished" = identityPoolOnly;
    };
}
2023-09-19 12:48:51.459634+0300 DesklessWorkers[1940:505563] [AuthenticationAWSCognitoAuthPlugin] Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.sessionEstablished" = identityPoolOnly;
    };
}

@brianmwadime
Copy link
Author

The amplify requests then return

APIError: Failed to retrieve authorization token.
Caused by:
AuthError: There is no user signed in to retreive cognito tokens
Recovery suggestion: Call Auth.signIn to sign in a user and then call Auth.fetchSession
  ▿ operationError : 3 elements
    - .0 : "Failed to retrieve authorization token."
    - .1 : ""
    ▿ .2 : Optional<Error>
      ▿ some : AuthError: There is no user signed in to retreive cognito tokens
Recovery suggestion: Call Auth.signIn to sign in a user and then call Auth.fetchSession
        ▿ signedOut : 3 elements
          - .0 : "There is no user signed in to retreive cognito tokens"
          - .1 : "Call Auth.signIn to sign in a user and then call Auth.fetchSession"
          - .2 : nil

@harsh62
Copy link
Member

harsh62 commented Sep 26, 2023

@brianmwadime

From the logs I can see that you were never signed in. I see that you have a valid AuthZ session. I see that you are trying to retrieve the Cognito Session from a featchAuthSessionAPI call. Cognito Session will only be available if a user is signed in. In your case, I see that no user has signed in.

Would you be able to share verbose logging for both scenarios that you are trying. It could help me understand what happened before and after.

@harsh62 harsh62 added the pending-community-response Issue is pending response from the issue requestor label Sep 26, 2023
@atierian atierian added the closing soon This issue will be closed in 7 days unless further comments are made. label Oct 9, 2023
@github-actions github-actions bot removed pending-community-response Issue is pending response from the issue requestor closing soon This issue will be closed in 7 days unless further comments are made. labels Oct 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auth Issues related to the Auth category question General question
Projects
None yet
Development

No branches or pull requests

4 participants