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

iOS Amplify Apple SignIn successfully but could not access other resources(S3) #3760

Closed
XingZhaoDev opened this issue Jun 20, 2024 · 12 comments
Labels
question General question storage Issues related to the Storage category

Comments

@XingZhaoDev
Copy link

XingZhaoDev commented Jun 20, 2024

Describe the bug

I have implemented Apple SignIn in my app, then I called "plugin.federateToIdentityPool()" and it is successful and I am able to fetch the credentials as well. BUT, when I called Amplify.Storage.uploadData(); I got error ""AuthError: Users Federated to Identity Pool do not have User Pool access.\nRecovery suggestion: To access User Pool data, you must use a Sign In method". Could you please help? I only wanted to have Apple SignIn in my app and do not want to create a custom SignIn flow or Cognito User Pool.

Steps To Reproduce

Steps to reproduce the behavior:
1. amplify init
2. amplify add auth (enable Apple SignIn), amplify add storage
3. Implement Apple SignIn in my SwiftUI app by myself not using "SignInWithWebUI"
4. Call "plugin.federateToIdentityPool" when Apple SignIn is done
5. Call "Amplify.Storage().uploadData()"
6. Get error: userSubError = "AuthError: Users Federated to Identity Pool do not have User Pool access.\nRecovery suggestion: To access User Pool data, you must use a Sign In method.";

Expected behavior

App should be able to access to S3 after SignIn with Apple account.

Amplify Framework Version

2.35.3

Amplify Categories

Storage

Dependency manager

Swift PM

Swift version

5.8

CLI version

12.12.2

Xcode version

Xcode 16.0

Relevant log output

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


Successfully completed execution for Auth.fetchSessionAPI with result:
{
    "AWS Credentials" = "[\"sessionToken\": \"IQ*****==\", \"expiration\": 2024-06-20 21:50:44 +0000, \"secretAccessKey\": \"DF*****NY\", \"accessKey\": \"AS*****WL\"]";
    cognitoTokensError = "AuthError: Users Federated to Identity Pool do not have User Pool access.\nRecovery suggestion: To access User Pool data, you must use a Sign In method.";
    identityId = "us-we*****1579e";
    isSignedIn = true;
    userSubError = "AuthError: Users Federated to Identity Pool do not have User Pool access.\nRecovery suggestion: To access User Pool data, you must use a Sign In method.";
}
```

Is this a regression?

No

Regression additional context

No response

Platforms

iOS

OS Version

15.0

Device

iPhone 13 PRO

Specific to simulators

No response

Additional context

No response

@harsh62 harsh62 added auth Issues related to the Auth category question General question labels Jun 21, 2024
@harsh62
Copy link
Member

harsh62 commented Jun 21, 2024

@XingZhaoDev Thank you for creating the issue. Would you be able to share the verbose logs when the issue is happening?

You can enable verbose logging to the console by doing this before calling Amplify.configure:

Amplify.Logging.logLevel = .verbose

@XingZhaoDev
Copy link
Author

@harsh62 hi, that's the logs I have. Thanks.
Screenshot 2024-06-20 at 8 56 53 PM

@harsh62
Copy link
Member

harsh62 commented Jun 21, 2024

@XingZhaoDev Did you enable verbose logging? And can you paste the entire log please?

In addition to that, could you also please paste code snippets that you have used for achieving the usecase?

@harsh62 harsh62 added the pending-response Issue is pending response from the issue requestor label Jun 21, 2024
@XingZhaoDev
Copy link
Author

XingZhaoDev commented Jun 21, 2024

@harsh62 I enabled verbose logging already. Below are the entire logs since app is launched

objc[56781]: Class _TtC6SQLite6Backup is implemented in both /System/Library/PrivateFrameworks/LinkServices.framework/LinkServices (0x202ad6370) and /private/var/containers/Bundle/Application/93C947EE-21D4-4D96-9D62-1B2D4FBF9FF3/AppleSignInAmplify.app/AppleSignInAmplify.debug.dylib (0x1166840b8). One of the two will be used. Which one is undefined.
objc[56781]: Class _TtC6SQLite10Connection is implemented in both /System/Library/PrivateFrameworks/LinkServices.framework/LinkServices (0x201e85818) and /private/var/containers/Bundle/Application/93C947EE-21D4-4D96-9D62-1B2D4FBF9FF3/AppleSignInAmplify.app/AppleSignInAmplify.debug.dylib (0x116684338). One of the two will be used. Which one is undefined.
objc[56781]: Class _TtC6SQLite9Statement is implemented in both /System/Library/PrivateFrameworks/LinkServices.framework/LinkServices (0x201e858e8) and /private/var/containers/Bundle/Application/93C947EE-21D4-4D96-9D62-1B2D4FBF9FF3/AppleSignInAmplify.app/AppleSignInAmplify.debug.dylib (0x1166844f8). One of the two will be used. Which one is undefined.
objc[56781]: Class _TtC6SQLite13DateFunctions is implemented in both /System/Library/PrivateFrameworks/LinkServices.framework/LinkServices (0x202ad62d8) and /private/var/containers/Bundle/Application/93C947EE-21D4-4D96-9D62-1B2D4FBF9FF3/AppleSignInAmplify.app/AppleSignInAmplify.debug.dylib (0x1166858e0). One of the two will be used. Which one is undefined.
objc[56781]: Class _TtC6SQLite12TableBuilder is implemented in both /System/Library/PrivateFrameworks/LinkServices.framework/LinkServices (0x202ad6138) and /private/var/containers/Bundle/Application/93C947EE-21D4-4D96-9D62-1B2D4FBF9FF3/AppleSignInAmplify.app/AppleSignInAmplify.debug.dylib (0x116685ce8). One of the two will be used. Which one is undefined.
Adding plugin: AWSCognitoAuthPlugin.AWSCognitoAuthPlugin)
Adding plugin: AWSS3StoragePlugin.AWSS3StoragePlugin)
Configuring
Configuration: nil
Auth state change:

{
    "AuthState.notConfigured" =     {
    };
}
Auth state change:

{
    "AuthState.configuringAuth" =     {
    };
}
Credential Store state change:

{
    "CredentialStoreState.notConfigured" =     {
    };
}
AWSCognitoAuthPlugin/InitializeAuthConfiguration.swift Starting execution
Credential Store state change:

{
    "CredentialStoreState.migratingLegacyStore" =     {
    };
}
AWSCognitoAuthPlugin/MigrateLegacyCredentialStore.swift Starting execution
[KeychainStore] Initialized keychain with service=com.amplify.awsCognitoAuthPlugin, attributes=KeychainStoreAttributes(itemClass: "genp", service: "com.amplify.awsCognitoAuthPlugin", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `Data` from the store with key=authConfiguration
[KeychainStore] Successfully retrieved `Data` from the store with key=authConfiguration
[KeychainStore] Started setting `Data` for key=authConfiguration
[KeychainStore] Initialized fetching to decide whether update or add
[KeychainStore] Found existing item, updating
[KeychainStore] Successfully updated `String` in keychain for key=authConfiguration
[KeychainStore] Initialized keychain with service=apple.signin.amplify.AWSCognitoIdentityUserPool, attributes=KeychainStoreAttributes(itemClass: "genp", service: "apple.signin.amplify.AWSCognitoIdentityUserPool", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `String` from the store with key=5rqvh0kpmhcscon7erbm0oivha.currentUser
[KeychainStore] Started retrieving `Data` from the store with key=5rqvh0kpmhcscon7erbm0oivha.currentUser
[KeychainStore] No Keychain item found for key=5rqvh0kpmhcscon7erbm0oivha.currentUser
[KeychainStore] Initialized keychain with service=apple.signin.amplify.AWSCognitoIdentityUserPool, attributes=KeychainStoreAttributes(itemClass: "genp", service: "apple.signin.amplify.AWSCognitoIdentityUserPool", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `String` from the store with key=5rqvh0kpmhcscon7erbm0oivha.currentUser
[KeychainStore] Started retrieving `Data` from the store with key=5rqvh0kpmhcscon7erbm0oivha.currentUser
[KeychainStore] No Keychain item found for key=5rqvh0kpmhcscon7erbm0oivha.currentUser
[KeychainStore] Starting to remove all items from keychain
[KeychainStore] Successfully removed all items from keychain
[KeychainStore] Initialized keychain with service=apple.signin.amplify.AWSCognitoCredentialsProvider.us-west-2:ab02345c-f7df-4504-8420-49c2c26bce40, attributes=KeychainStoreAttributes(itemClass: "genp", service: "apple.signin.amplify.AWSCognitoCredentialsProvider.us-west-2:ab02345c-f7df-4504-8420-49c2c26bce40", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `String` from the store with key=accessKey
[KeychainStore] Started retrieving `Data` from the store with key=accessKey
[KeychainStore] No Keychain item found for key=accessKey
[KeychainStore] Starting to remove all items from keychain
[KeychainStore] Successfully removed all items from keychain
[KeychainStore] Initialized keychain with service=Optional("apple.signin.amplify").AWSMobileClient, attributes=KeychainStoreAttributes(itemClass: "genp", service: "Optional(\"apple.signin.amplify\").AWSMobileClient", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `Data` from the store with key=loginsMap
[KeychainStore] No Keychain item found for key=loginsMap
[KeychainStore] Initialized keychain with service=Optional("apple.signin.amplify").AWSMobileClient, attributes=KeychainStoreAttributes(itemClass: "genp", service: "Optional(\"apple.signin.amplify\").AWSMobileClient", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `String` from the store with key=federationProvider
[KeychainStore] Started retrieving `Data` from the store with key=federationProvider
[KeychainStore] No Keychain item found for key=federationProvider
[KeychainStore] Starting to remove all items from keychain
[KeychainStore] Successfully removed all items from keychain
AWSCognitoAuthPlugin/MigrateLegacyCredentialStore.swift Sending event CredentialStoreEvent.loadCredentialStore
Credential Store state change:

{
    "CredentialStoreState.loadingStoredCredentials" =     {
    };
}
AWSCognitoAuthPlugin/LoadCredentialStore.swift Starting execution
AWSCognitoAuthPlugin/LoadCredentialStore.swift Retreiving credential amplifyCredentials
[KeychainStore] Initialized keychain with service=com.amplify.awsCognitoAuthPlugin, attributes=KeychainStoreAttributes(itemClass: "genp", service: "com.amplify.awsCognitoAuthPlugin", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `Data` from the store with key=authConfiguration
[KeychainStore] Successfully retrieved `Data` from the store with key=authConfiguration
[KeychainStore] Started setting `Data` for key=authConfiguration
[KeychainStore] Initialized fetching to decide whether update or add
[KeychainStore] Found existing item, updating
[KeychainStore] Successfully updated `String` in keychain for key=authConfiguration
[KeychainStore] Started retrieving `Data` from the store with key=amplify.us-west-2_MgQAwiN2q.us-west-2:ab02345c-f7df-4504-8420-49c2c26bce40.session
[KeychainStore] Successfully retrieved `Data` from the store with key=amplify.us-west-2_MgQAwiN2q.us-west-2:ab02345c-f7df-4504-8420-49c2c26bce40.session
Successfully configured Amplify
Recovery completed: [pairs = 0]
Unable to create bundle at URL (file:///System/Library/CoreServices/SystemVersion.bundle): does not exist or not a directory (0)
Unable to create bundle at URL (file:///System/Library/CoreServices/SystemVersion.bundle): does not exist or not a directory (0)
Unable to create bundle at URL (file:///System/Library/CoreServices/SystemVersion.bundle): does not exist or not a directory (0)
AWSCognitoAuthPlugin/LoadCredentialStore.swift Sending event CredentialStoreEvent.completedOperation
AWSCognitoAuthPlugin/InitializeAuthConfiguration.swift Sending event AuthEvent.validateCredentialAndConfiguration
Auth state change:

{
    "AuthState.validatingCredentialsAndConfiguration" =     {
    };
}
AWSCognitoAuthPlugin/IdleCredentialStore.swift Starting execution
AWSCognitoAuthPlugin/IdleCredentialStore.swift Sending event CredentialStoreEvent.moveToIdleState
AWSCognitoAuthPlugin/ValidateCredentialsAndConfiguration.swift Starting execution
AWSCognitoAuthPlugin/ValidateCredentialsAndConfiguration.swift Sending event AuthEvent.configureAuthentication
Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.notConfigured" =         {
        };
    };
}
AWSCognitoAuthPlugin/InitializeAuthenticationConfiguration.swift Starting execution
AWSCognitoAuthPlugin/InitializeAuthenticationConfiguration.swift Sending event AuthenticationEvent.configure
AWSCognitoAuthPlugin/ConfigureAuthentication.swift Start execution
AWSCognitoAuthPlugin/ConfigureAuthentication.swift Sending event AuthenticationEvent.initializedFederated
AWSCognitoAuthPlugin/ConfigureAuthentication.swift Sending event AuthEvent.authenticationConfigured
Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.configured" =         {
        };
    };
}
Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.federatedToIdentityPool" =         {
        };
    };
}
AWSCognitoAuthPlugin/InitializeAuthorizationConfiguration.swift Starting execution
Auth state change:

{
    "AuthState.configuringAuthorization" =     {
        "AuthenticationState.federatedToIdentityPool" =         {
        };
        "AuthorizationState.notConfigured" =         {
        };
    };
}
AWSCognitoAuthPlugin/InitializeAuthorizationConfiguration.swift Sending event AuthorizationEvent.cachedCredentialsAvailable
AWSCognitoAuthPlugin/ConfigureAuthorization.swift Starting execution
AWSCognitoAuthPlugin/ConfigureAuthorization.swift Sending event AuthEvent.authorizationConfigured
Auth state change:

{
    "AuthState.configuringAuthorization" =     {
        "AuthenticationState.federatedToIdentityPool" =         {
        };
        "AuthorizationState.sessionEstablished" = identityPoolWithFederation;
    };
}
Credential Store state change:

{
    "CredentialStoreState.success" =     {
        savedData = "AWSCognitoAuthPlugin.CredentialStoreData.amplifyCredentials(identityPoolWithFederation)";
    };
}
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatedToIdentityPool" =         {
        };
        "AuthorizationState.sessionEstablished" = identityPoolWithFederation;
    };
}
Credential Store state change:

{
    "CredentialStoreState.idle" =     {
    };
}
CoreGraphics PDF has logged an error. Set environment variable "CG_PDF_VERBOSE" to learn more.
Failed to send CA Event for app launch measurements for ca_event_type: 1 event_name: com.apple.app_launch_measurement.ExtendedLaunchMetrics
Token is 821 bytes
Starting execution for Auth.federatedToIdentityPool
Starting execution
Check if authstate configured
Auth state configured
Waiting for federation to complete
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.federatingToIdentityPool" =         {
            "FetchSessionState.notStarted" =             {
            };
        };
    };
}
AWSCognitoAuthPlugin/InitializeFederationToIdentityPool.swift Starting execution
AWSCognitoAuthPlugin/InitializeFederationToIdentityPool.swift Sending event FetchAuthSessionEvent.fetchAuthenticatedIdentityID
AWSCognitoAuthPlugin/FetchAuthIdentityId.swift Starting execution
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.federatingToIdentityPool" =         {
            "FetchSessionState.fetchingIdentityID" =             {
            };
        };
    };
}
2024-06-21T08:49:33-0700 info CognitoIdentityClient : [Logging] Request: POST https:443 
 Path: / 
 X-Amz-Target: AWSCognitoIdentityService.GetId, 
Content-Type: application/x-amz-json-1.1, 
Host: cognito-identity.us-west-2.amazonaws.com, 
User-Agent: aws-sdk-swift/1.0 ua/2.0 api/cognito_identity#1.0 os/ios#18.0.0 lang/swift#5.10 cfg/retry-mode#legacy, 
Content-Length: 922 
 nil
AWSCognitoAuthPlugin/FetchAuthIdentityId.swift Sending event FetchAuthSessionEvent.fetchedIdentityID
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.federatingToIdentityPool" =         {
            "FetchSessionState.fetchingAWSCredentials" =             {
            };
        };
    };
}
AWSCognitoAuthPlugin/FetchAuthAWSCredentials.swift Starting execution
2024-06-21T08:49:34-0700 info CognitoIdentityClient : [Logging] Request: POST https:443 
 Path: / 
 Host: cognito-identity.us-west-2.amazonaws.com, 
X-Amz-Target: AWSCognitoIdentityService.GetCredentialsForIdentity, 
Content-Length: 918, 
User-Agent: aws-sdk-swift/1.0 ua/2.0 api/cognito_identity#1.0 os/ios#18.0.0 lang/swift#5.10 cfg/retry-mode#legacy, 
Content-Type: application/x-amz-json-1.1 
 nil
AWSCognitoAuthPlugin/FetchAuthAWSCredentials.swift Sending event FetchAuthSessionEvent.fetchedAWSCredentials
AWSCognitoAuthPlugin/InformSessionFetched.swift Starting execution
AWSCognitoAuthPlugin/InformSessionFetched.swift Sending event AuthorizationEvent.fetched
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.federatingToIdentityPool" =         {
            "FetchSessionState.fetched" =             {
            };
        };
    };
}
AWSCognitoAuthPlugin/PersistCredentials.swift Starting execution
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.storingCredentials" = identityPoolWithFederation;
    };
}
Credential Store state change:

{
    "CredentialStoreState.storingCredentials" =     {
    };
}
AWSCognitoAuthPlugin/StoreCredentials.swift Starting execution
[KeychainStore] Initialized keychain with service=com.amplify.awsCognitoAuthPlugin, attributes=KeychainStoreAttributes(itemClass: "genp", service: "com.amplify.awsCognitoAuthPlugin", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `Data` from the store with key=authConfiguration
[KeychainStore] Successfully retrieved `Data` from the store with key=authConfiguration
[KeychainStore] Started setting `Data` for key=authConfiguration
[KeychainStore] Initialized fetching to decide whether update or add
[KeychainStore] Found existing item, updating
[KeychainStore] Successfully updated `String` in keychain for key=authConfiguration
[KeychainStore] Started setting `Data` for key=amplify.us-west-2_MgQAwiN2q.us-west-2:ab02345c-f7df-4504-8420-49c2c26bce40.session
[KeychainStore] Initialized fetching to decide whether update or add
[KeychainStore] Found existing item, updating
[KeychainStore] Successfully updated `String` in keychain for key=amplify.us-west-2_MgQAwiN2q.us-west-2:ab02345c-f7df-4504-8420-49c2c26bce40.session
AWSCognitoAuthPlugin/StoreCredentials.swift Sending event CredentialStoreEvent.completedOperation
AWSCognitoAuthPlugin/IdleCredentialStore.swift Starting execution
AWSCognitoAuthPlugin/IdleCredentialStore.swift Sending event CredentialStoreEvent.moveToIdleState
AWSCognitoAuthPlugin/PersistCredentials.swift Sending event AuthorizationEvent.sessionEstablished
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatedToIdentityPool" =         {
        };
        "AuthorizationState.sessionEstablished" = identityPoolWithFederation;
    };
}
Credential Store state change:

{
    "CredentialStoreState.success" =     {
        savedData = "AWSCognitoAuthPlugin.CredentialStoreData.amplifyCredentials(identityPoolWithFederation)";
    };
}
Credential Store state change:

{
    "CredentialStoreState.idle" =     {
    };
}
Successfully completed execution for Auth.federatedToIdentityPool with result:
FederateToIdentityPoolResult(credentials: ["accessKey": "AS*****OO", "secretAccessKey": "eb*****XH", "expiration": 2024-06-21 16:49:34 +0000, "sessionToken": "IQ*****=="], identityId: "us-west-2:d1ab1d7e-34db-cc13-e2f6-4288f6a1579e")
Successfully federated user to identity pool with result: FederateToIdentityPoolResult(credentials: ["accessKey": "AS*****OO", "secretAccessKey": "eb*****XH", "expiration": 2024-06-21 16:49:34 +0000, "sessionToken": "IQ*****=="], identityId: "us-west-2:d1ab1d7e-34db-cc13-e2f6-4288f6a1579e")
2024-06-21T08:49:37-0700 info S3Client : [Logging] No checksum provided! Skipping flexible checksums workflow...
Starting execution for Auth.fetchSessionAPI
Starting execution
Check if authstate configured
Auth state configured
Fetching current state
Session exists, checking validity
Successfully completed execution for Auth.fetchSessionAPI with result:
{
    "AWS Credentials" = "[\"accessKey\": \"AS*****OO\", \"secretAccessKey\": \"eb*****XH\", \"sessionToken\": \"IQ*****==\", \"expiration\": 2024-06-21 16:49:34 +0000]";
    cognitoTokensError = "AuthError: Users Federated to Identity Pool do not have User Pool access.\nRecovery suggestion: To access User Pool data, you must use a Sign In method.";
    identityId = "us-we*****1579e";
    isSignedIn = true;
    userSubError = "AuthError: Users Federated to Identity Pool do not have User Pool access.\nRecovery suggestion: To access User Pool data, you must use a Sign In method.";
}
Started upload [1]
Resuming storage transfer task: 1
[URLSession] Session task update: [bytesSent: 1042382], [totalBytesSent: 1042382], [totalBytesExpectedToSend: 1042382]
Photo uploading Progress: <NSProgress: 0x300da6c80> : Parent: 0x0 (portion: 0) / Fraction completed: 1.0000 / Completed: 1042382 of 1042382  
[URLSession] Session task did complete: 1
[URLSession] Failed with error: StorageError: The HTTP response status code is [400].
Recovery suggestion: Client error.
For more information on HTTP status codes, take a look at
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue requestor label Jun 21, 2024
@XingZhaoDev
Copy link
Author

XingZhaoDev commented Jun 21, 2024

What I am doing is:

  1. Add plugins "AWSCognitoAuthPlugin" and "AWSS3StoragePlugin"
  2. SignIn with Apple ID using SignInWithAppleButton in SwiftUI
  3. Send the token via 'plugin.federateToIdentityPool' after sign in
  4. Upload a file to S3

https://aws.amazon.com/blogs/mobile/federating-users-using-sign-in-with-apple-and-aws-amplify-for-swift/

@XingZhaoDev
Copy link
Author

XingZhaoDev commented Jun 21, 2024

  1. Setup Amplify
@main
struct AppleSignInAmplifyApp: App {
    init() {
        configureAmplify()
    }
    
    func configureAmplify() {
        do {
            Amplify.Logging.logLevel = .verbose
            try Amplify.add(plugin: AWSCognitoAuthPlugin())
            try Amplify.add(plugin: AWSS3StoragePlugin())
            try Amplify.configure()
            print("Successfully configured Amplify")
        } catch {
            print("Failed to initialize Amplify:", error)
        }
    }
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

@XingZhaoDev
Copy link
Author

XingZhaoDev commented Jun 21, 2024

  1. SignIn with Apple and send token to Identity pool, upload file in ContentView
struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            SignInWithAppleButton(
                onRequest: configureRequest,
                onCompletion: handleResult
            )
            .frame(maxWidth: 300, maxHeight: 45)
            
            Button("Upload") {
                Task {
                    try await uploadImageToS3()
                }
            }
            Image("ronaldo")
                .resizable()
                .aspectRatio(contentMode: .fit)
        }
        .padding()
    }
    
    func uploadDataToS3() async throws {
        let dataString = "My Data"
        let data = Data(dataString.utf8)
        let uploadTask = Amplify.Storage.uploadData(
            path: .fromString("public/example/path"),
            data: data
        )
        Task {
            for await progress in await uploadTask.progress {
                print("Progress: \(progress)")
            }
        }
        let value = try await uploadTask.value
        print("Completed: \(value)")
    }
    
    func uploadImageToS3() async throws {
        guard let targetImage = UIImage(named: "ronaldo") else {
            print("targetImage is nil")
            return
        }
        guard let imageData = targetImage.jpegData(compressionQuality: 1) else {
            print("JPEG data is nil")
            return
        }
        let uploadTask = Amplify.Storage.uploadData(path: .fromString("Images/ronaldo.png"), data: imageData)
        Task {
            for await progress in await uploadTask.progress {
                print("Photo uploading Progress: \(progress)")
            }
        }
        let data = try await uploadTask.value
        print("Photo uploading Completed: \(data)")
    }
    
    func configureRequest(_ request: ASAuthorizationAppleIDRequest) {
        request.requestedScopes = [.email]
    }

    func handleResult(_ result: Result<ASAuthorization, Error>) {
        switch result {
        case .success(let authorization):
            guard
                let credential = authorization.credential as? ASAuthorizationAppleIDCredential,
                let identityToken = credential.identityToken
            else { return }
            print("Token is \(identityToken)")
            federateToIdentityPools(with: identityToken)
        case .failure(let error):
            print(error)
        }
    }
    
    func federateToIdentityPools(with token: Data) {
        guard
            let tokenString = String(data: token, encoding: .utf8),
            let plugin = try? Amplify.Auth.getPlugin(for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
        else { return }
        Task {
            do {
                let result = try await plugin.federateToIdentityPool(
                    withProviderToken: tokenString,
                    for: .apple
                    
            
                )
                print("Successfully federated user to identity pool with result:", result)
            } catch {
                print("Failed to federate to identity pool with error:", error)
            }
        }
    }

@XingZhaoDev
Copy link
Author

amplifyconfiguration.json is here:

{
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "auth": {
        "plugins": {
            "awsCognitoAuthPlugin": {
                "UserAgent": "aws-amplify/cli",
                "Version": "0.1.0",
                "IdentityManager": {
                    "Default": {}
                },
                "CredentialsProvider": {
                    "CognitoIdentity": {
                        "Default": {
                            "PoolId": "######",
                            "Region": "us-west-2"
                        }
                    }
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "#######",
                        "AppClientId": "######",
                        "Region": "us-west-2"
                    }
                },
                "Auth": {
                    "Default": {
                        "authenticationFlowType": "USER_SRP_AUTH",
                        "socialProviders": [],
                        "usernameAttributes": [],
                        "signupAttributes": [
                            "EMAIL"
                        ],
                        "passwordProtectionSettings": {
                            "passwordPolicyMinLength": 8,
                            "passwordPolicyCharacters": []
                        },
                        "mfaConfiguration": "OFF",
                        "mfaTypes": [
                            "SMS"
                        ],
                        "verificationMechanisms": [
                            "EMAIL"
                        ]
                    }
                }
            }
        }
    },
    "storage": {
        "plugins": {
            "awsS3StoragePlugin": {
                "bucket": "########",
                "region": "us-west-2"
            }
        }
    }
}

@XingZhaoDev XingZhaoDev changed the title iOS Amplify Apple SignIn successfully but could not access to other resources(S3) iOS Amplify Apple SignIn successfully but could not access other resources(S3) Jun 21, 2024
@harsh62
Copy link
Member

harsh62 commented Jun 25, 2024

@XingZhaoDev

I see that you are not creating the path correctly while uploading an image..

        let uploadTask = Amplify.Storage.uploadData(path: .fromString("Images/ronaldo.png"), data: imageData)

The path should look something like this .fromString("public/ronaldo.png"). If you do that, I think everything should work correctly.

@harsh62 harsh62 added storage Issues related to the Storage category and removed auth Issues related to the Auth category labels Jun 25, 2024
@XingZhaoDev
Copy link
Author

hi @harsh62 Thanks for the reply, I just encountered a weird thing that the uploading works even when the path is "Images/ronaldo.png", and I did not even change anything. Thanks.

@harsh62
Copy link
Member

harsh62 commented Jun 25, 2024

I would recommend going through the documentation to better understand how paths work.

From the docs:

By default, no users or other project resources have access to any files in the storage bucket. Access must be explicitly granted within defineStorage using the access callback.

The access callback returns an object where each key in the object is a file path and each value in the object is an array of access rules that apply to that path.

export const storage = defineStorage({
  name: 'amplifyTeamDrive',
  access: (allow) => ({
    'profile-pictures/{entity_id}/*': [
      allow.guest.to(['read']),
      allow.entity('identity').to(['read', 'write', 'delete'])
    ],
    'picture-submissions/*': [
      allow.authenticated.to(['read','write']),
      allow.guest.to(['read', 'write'])
    ],
  })
});

@harsh62 harsh62 closed this as completed Jun 25, 2024
Copy link
Contributor

This issue is now closed. Comments on closed issues are hard for our team to see.
If you need more assistance, please open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question General question storage Issues related to the Storage category
Projects
None yet
Development

No branches or pull requests

2 participants