Skip to content

Unable to get Sign in with Apple to work #3952

@johndebord

Description

@johndebord

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" =         {
        };
    };
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    authIssues related to the Auth categorybugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions