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

Unable to get Sign in with Apple to work #3952

Closed
johndebord opened this issue Jan 21, 2025 · 6 comments
Closed

Unable to get Sign in with Apple to work #3952

johndebord opened this issue Jan 21, 2025 · 6 comments
Labels
auth Issues related to the Auth category bug Something isn't working

Comments

@johndebord
Copy link

johndebord commented Jan 21, 2025

I am encountering an issue with implementing Sign in with Apple. While the sign-in flow initiates as expected, it ultimately fails to complete successfully. I have followed the configuration steps carefully, but I may have missed something. It is unclear whether this is related to IAM permissions; if so, I am unsure which permissions need to be assigned to which service or what specific permissions are required.

I am using Amplify 2.45.3


Here's the relevant code:

import Amplify
import AuthenticationServices
import AWSCognitoAuthPlugin
import SwiftUI

struct AuthenticationView: View {
    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 }
            self.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)
            }
        }
    }

    var body: some View {
        SignInWithAppleButton(
            onRequest: self.configureRequest,
            onCompletion: self.handleResult
        ).frame(maxWidth: 300, maxHeight: 45)
    }
}

Here's my resource.ts file:

import { defineAuth, secret } from "@aws-amplify/backend";

export const auth = defineAuth({
  loginWith: {
    externalProviders: {
      signInWithApple: {
        clientId: secret("SIWA_CLIENT_ID"),
        keyId: secret("SIWA_KEY_ID"),
        privateKey: secret("SIWA_PRIVATE_KEY"),
        teamId: secret("SIWA_TEAM_ID"),
      },
      callbackUrls: ["http://localhost:3000/"],
      logoutUrls: ["http://localhost:3000/"],
    },
  },
});

Here's my verbose logs:

Error creating the CFMessagePort needed to communicate with PPT.
Starting execution for Auth.fetchSessionAPI
Check if authstate configured
[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 `Data` in keychain for key=authConfiguration
[KeychainStore] Initialized keychain with service=app.piecely.AWSCognitoIdentityUserPool, attributes=KeychainStoreAttributes(itemClass: "genp", service: "app.piecely.AWSCognitoIdentityUserPool", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `String` from the store with key=55pvlvih0sioaphqlsrmpvfso5.currentUser
[KeychainStore] Started retrieving `Data` from the store with key=55pvlvih0sioaphqlsrmpvfso5.currentUser
[KeychainStore] No Keychain item found for key=55pvlvih0sioaphqlsrmpvfso5.currentUser
[KeychainStore] Initialized keychain with service=app.piecely.AWSCognitoIdentityUserPool, attributes=KeychainStoreAttributes(itemClass: "genp", service: "app.piecely.AWSCognitoIdentityUserPool", accessGroup: nil), accessGroup=
[KeychainStore] Started retrieving `String` from the store with key=55pvlvih0sioaphqlsrmpvfso5.currentUser
[KeychainStore] Started retrieving `Data` from the store with key=55pvlvih0sioaphqlsrmpvfso5.currentUser
[KeychainStore] No Keychain item found for key=55pvlvih0sioaphqlsrmpvfso5.currentUser
[KeychainStore] Starting to remove all items from keychain
[KeychainStore] Successfully removed all items from keychain
[KeychainStore] Initialized keychain with service=app.piecely.AWSCognitoCredentialsProvider.us-east-1:dbb58eb4-6210-42a5-b290-a833df09ea3c, attributes=KeychainStoreAttributes(itemClass: "genp", service: "app.piecely.AWSCognitoCredentialsProvider.us-east-1:dbb58eb4-6210-42a5-b290-a833df09ea3c", 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("app.piecely").AWSMobileClient, attributes=KeychainStoreAttributes(itemClass: "genp", service: "Optional(\"app.piecely\").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("app.piecely").AWSMobileClient, attributes=KeychainStoreAttributes(itemClass: "genp", service: "Optional(\"app.piecely\").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
AWSCognitoAuthPlugin/LoadCredentialStore.swift Starting execution
Credential Store state change:

{
    "CredentialStoreState.loadingStoredCredentials" =     {
    };
}
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 `Data` in keychain for key=authConfiguration
[KeychainStore] Started retrieving `Data` from the store with key=amplify.us-east-1_hNIO7fLMx.us-east-1:dbb58eb4-6210-42a5-b290-a833df09ea3c.session
[KeychainStore] Successfully retrieved `Data` from the store with key=amplify.us-east-1_hNIO7fLMx.us-east-1:dbb58eb4-6210-42a5-b290-a833df09ea3c.session
AWSCognitoAuthPlugin/LoadCredentialStore.swift Sending event CredentialStoreEvent.completedOperation
AWSCognitoAuthPlugin/IdleCredentialStore.swift Starting execution
AWSCognitoAuthPlugin/IdleCredentialStore.swift Sending event CredentialStoreEvent.moveToIdleState
AWSCognitoAuthPlugin/InitializeAuthConfiguration.swift Sending event AuthEvent.validateCredentialAndConfiguration
Auth state change:

{
    "AuthState.validatingCredentialsAndConfiguration" =     {
    };
}
AWSCognitoAuthPlugin/ValidateCredentialsAndConfiguration.swift Starting execution
AWSCognitoAuthPlugin/ValidateCredentialsAndConfiguration.swift Sending event AuthEvent.configureAuthentication
Credential Store state change:

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

{
    "CredentialStoreState.idle" =     {
    };
}
Auth state change:

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

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.configured" =         {
        };
    };
}
AWSCognitoAuthPlugin/ConfigureAuthentication.swift Start execution
AWSCognitoAuthPlugin/ConfigureAuthentication.swift Sending event AuthenticationEvent.initializedSignedOut
AWSCognitoAuthPlugin/ConfigureAuthentication.swift Sending event AuthEvent.authenticationConfigured
Auth state change:

{
    "AuthState.configuringAuthentication" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
    };
}
Auth state change:

{
    "AuthState.configuringAuthorization" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.notConfigured" =         {
        };
    };
}
AWSCognitoAuthPlugin/InitializeAuthorizationConfiguration.swift Starting execution
AWSCognitoAuthPlugin/InitializeAuthorizationConfiguration.swift Sending event AuthorizationEvent.cachedCredentialsAvailable
Auth state change:

{
    "AuthState.configuringAuthorization" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.sessionEstablished" = identityPoolOnly;
    };
}
AWSCognitoAuthPlugin/ConfigureAuthorization.swift Starting execution
AWSCognitoAuthPlugin/ConfigureAuthorization.swift Sending event AuthEvent.authorizationConfigured
Auth state configured
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.sessionEstablished" = identityPoolOnly;
        "SignUpState.notStarted" =         {
        };
    };
}
Fetching current state
Session exists, checking validity
Waiting for session to establish
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.refreshingSession" =         {
            existing = identityPoolOnly;
            refreshState =             {
                "RefreshSessionState.notStarted" =                 {
                };
            };
        };
        "SignUpState.notStarted" =         {
        };
    };
}
AWSCognitoAuthPlugin/InitializeRefreshSession.swift Starting execution
AWSCognitoAuthPlugin/InitializeRefreshSession.swift Sending event RefreshSessionEvent.refreshUnAuthAWSCredentials
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.refreshingSession" =         {
            existing = identityPoolOnly;
            refreshState =             {
                "RefreshSessionState.refreshingUnAuthAWSCredentials" =                 {
                };
            };
        };
        "SignUpState.notStarted" =         {
        };
    };
}
AWSCognitoAuthPlugin/FetchAuthAWSCredentials.swift Starting execution
AWSCognitoAuthPlugin/FetchAuthAWSCredentials.swift Sending event FetchAuthSessionEvent.fetchedAWSCredentials
AWSCognitoAuthPlugin/InformSessionRefreshed.swift Starting execution
AWSCognitoAuthPlugin/InformSessionRefreshed.swift Sending event AuthorizationEvent.refreshed
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.refreshingSession" =         {
            existing = identityPoolOnly;
            refreshState =             {
                "RefreshSessionState.refreshed" =                 {
                };
            };
        };
        "SignUpState.notStarted" =         {
        };
    };
}
AWSCognitoAuthPlugin/PersistCredentials.swift Starting execution
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.storingCredentials" = identityPoolOnly;
        "SignUpState.notStarted" =         {
        };
    };
}
AWSCognitoAuthPlugin/StoreCredentials.swift Starting execution
Credential Store state change:

{
    "CredentialStoreState.storingCredentials" =     {
    };
}
[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 `Data` in keychain for key=authConfiguration
[KeychainStore] Started setting `Data` for key=amplify.us-east-1_hNIO7fLMx.us-east-1:dbb58eb4-6210-42a5-b290-a833df09ea3c.session
[KeychainStore] Initialized fetching to decide whether update or add
[KeychainStore] Found existing item, updating
[KeychainStore] Successfully updated `Data` in keychain for key=amplify.us-east-1_hNIO7fLMx.us-east-1:dbb58eb4-6210-42a5-b290-a833df09ea3c.session
AWSCognitoAuthPlugin/StoreCredentials.swift Sending event CredentialStoreEvent.completedOperation
AWSCognitoAuthPlugin/IdleCredentialStore.swift Starting execution
AWSCognitoAuthPlugin/IdleCredentialStore.swift Sending event CredentialStoreEvent.moveToIdleState
Credential Store state change:

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

{
    "CredentialStoreState.idle" =     {
    };
}
AWSCognitoAuthPlugin/PersistCredentials.swift Sending event AuthorizationEvent.sessionEstablished
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.signedOut" =         {
            lastKnownUserName = "(nil)";
        };
        "AuthorizationState.sessionEstablished" = identityPoolOnly;
        "SignUpState.notStarted" =         {
        };
    };
}
Successfully completed execution for Auth.fetchSessionAPI with result:
{
    "AWS Credentials" = "[\"accessKey\": \"AS*****H7\", \"expiration\": 2025-01-21 10:16:00 +0000, \"sessionToken\": \"IQ*****c=\", \"secretAccessKey\": \"ff*****I3\"]";
    cognitoTokensError = "AuthError: There is no user signed in to retreive cognito tokens\nRecovery suggestion: Call Auth.signIn to sign in a user and then call Auth.fetchSession";
    identityId = "us-ea*****e8540";
    isSignedIn = false;
    userSubError = "AuthError: There is no user signed in to retreive user sub\nRecovery suggestion: Call Auth.signIn to sign in a user and then call Auth.fetchSession";
}
AppStateObservableObject::configureAmplify::Success
Starting execution for Auth.federatedToIdentityPool
Check if authstate configured
Auth state configured
Waiting for federation to complete
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.federatingToIdentityPool" =         {
            "FetchSessionState.notStarted" =             {
            };
        };
        "SignUpState.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" =             {
            };
        };
        "SignUpState.notStarted" =         {
        };
    };
}
AWSCognitoAuthPlugin/FetchAuthIdentityId.swift Sending event FetchAuthSessionEvent.throwError
AWSCognitoAuthPlugin/InformSessionError.swift Starting execution
AWSCognitoAuthPlugin/InformSessionError.swift Sending event AuthorizationEvent.receivedSessionError
Failed execution for Auth.federatedToIdentityPool with error:
AuthError: Not authorized error
Recovery suggestion: Check whether the given values are correct and the user is authorized to perform the operation
Failed to federate to identity pool with error: 
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.federatingToIdentityPool" =         {
        };
        "AuthorizationState.federatingToIdentityPool" =         {
            "FetchSessionState.error" =             {
                error = "AWSCognitoAuthPlugin.FetchSessionError.notAuthorized";
            };
        };
        "SignUpState.notStarted" =         {
        };
    };
}
AuthError: Not authorized error
Recovery suggestion: Check whether the given values are correct and the user is authorized to perform the operation
Auth state change:

{
    "AuthState.configured" =     {
        "AuthenticationState.error" =         {
            Error = "AWSCognitoAuthPlugin.AuthenticationError.service(message: \"Session error: notAuthorized\", error: Optional(AWSCognitoAuthPlugin.FetchSessionError.notAuthorized))";
        };
        "AuthorizationState.error" =         {
            Error = "AWSCognitoAuthPlugin.AuthorizationError.sessionError(AWSCognitoAuthPlugin.FetchSessionError.notAuthorized, identityPoolOnly)";
        };
        "SignUpState.notStarted" =         {
        };
    };
}
@github-actions github-actions bot added pending-triage Issue is pending triage pending-maintainer-response Issue is pending response from an Amplify team member labels Jan 21, 2025
@thisisabhash
Copy link
Member

Thank you for posting this - our team will take a look and post updates here.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending response from an Amplify team member label Jan 21, 2025
@thisisabhash thisisabhash added bug Something isn't working auth Issues related to the Auth category pending-maintainer-response Issue is pending response from an Amplify team member and removed pending-triage Issue is pending triage pending-maintainer-response Issue is pending response from an Amplify team member labels Jan 21, 2025
@johndebord
Copy link
Author

Thank you for posting this - our team will take a look and post updates here.

Please let me know if there is any additional information I can provide to help diagnose the issue.

@github-actions github-actions bot added the pending-maintainer-response Issue is pending response from an Amplify team member label Jan 21, 2025
@harsh62
Copy link
Member

harsh62 commented Jan 23, 2025

@johndebord Unfortunately native Sign in with Apple is not supported. There is already a feature request open with the service team to work on this.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending response from an Amplify team member label Jan 23, 2025
@johndebord
Copy link
Author

johndebord commented Jan 23, 2025

@harsh62 Thank you for the response. I’m confused—is this blog post from AWS obsolete?
https://aws.amazon.com/blogs/mobile/federating-users-using-sign-in-with-apple-and-aws-amplify-for-swift/

@github-actions github-actions bot added the pending-maintainer-response Issue is pending response from an Amplify team member label Jan 23, 2025
@harsh62
Copy link
Member

harsh62 commented Jan 24, 2025

What you are trying to do is federate into AWS using Cognito Identity. That should still work.

In the original issue you've setup Amplify as follows

loginWith: {
    externalProviders: {
      signInWithApple: {
        clientId: secret("SIWA_CLIENT_ID"),
        keyId: secret("SIWA_KEY_ID"),
        privateKey: secret("SIWA_PRIVATE_KEY"),
        teamId: secret("SIWA_TEAM_ID"),
      },
      callbackUrls: ["http://localhost:3000/"],
      logoutUrls: ["http://localhost:3000/"],
    },
  },

This means that you are trying to federate into AWS Cognito User Pools which is not supported with native Apple Sign in.


In the tutorial, they have shown a way to setup AWS Cognito Identity using CLI. Which should still work.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending response from an Amplify team member label Jan 24, 2025
@harsh62 harsh62 closed this as completed Jan 31, 2025
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
auth Issues related to the Auth category bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants