Sobes.tech
Middle+

How to implement Apple authentication in an iOS application?

sobes.tech AI

Answer from AI

To implement Sign In with Apple on an iOS app, the following steps are necessary:

  1. Configure your app in the Apple Developer Portal:

    • Enable the "Sign In with Apple" capability for your App ID.
    • Generate or update a Provisioning Profile with the capability enabled.
  2. Add the "Sign In with Apple" capability to your Xcode project.

  3. Use the AuthenticationServices framework.

Example code to initiate the authorization request:

import AuthenticationServices

@available(iOS 13.0, *)
func performSignInWithApple() {
    // Create provider
    let appleIDProvider = ASAuthorizationAppleIDProvider()

    // Create request
    let request = appleIDProvider.createRequest()
    request.requestedScopes = [.fullName, .email] // Request user's name and email

    // Create controller to handle requests
    let authorizationController = ASAuthorizationController(authorizationRequests: [request])

    // Set delegates to handle responses
    authorizationController.delegate = self
    authorizationController.presentationContextProvider = self

    // Start the authorization process
    authorizationController.performRequests()
}

// Delegate implementations
// ASAuthorizationControllerDelegate
@available(iOS 13.0, *)
extension YourViewController: ASAuthorizationControllerDelegate {
    // Handle successful authorization
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            let userIdentifier = appleIDCredential.user // Unique Apple user ID
            let fullName = appleIDCredential.fullName // User's name
            let email = appleIDCredential.email // User's email (available only on first login)

            // Send userIdentifier and other data to your server for verification and account creation/linking
            print("User ID: \(userIdentifier)")
            print("Full Name: \(fullName?.givenName ?? "") \(fullName?.familyName ?? "")")
            print("Email: \(email ?? "")")
        } else if let passwordCredential = authorization.credential as? ASPasswordCredential {
            // User used saved passwords from iCloud Keychain
            let username = passwordCredential.user
            let password = passwordCredential.password
            // Use these data for login
            print("Username: \(username)")
            print("Password: \(password)")
        }
    }

    // Handle authorization error
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        print("Sign in with Apple failed: \(error.localizedDescription)")
        // Handle errors (e.g., user canceled authorization)
    }
}

// ASAuthorizationControllerPresentationContextProviding
@available(iOS 13.0, *)
extension YourViewController: ASAuthorizationControllerPresentationContextProviding {
    // Provide the window on which the authorization interface will be shown
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return view.window! // Ensure to return a non-nil window
    }
}

// TODO: Ensure YourViewController conforms to the necessary protocols.
  1. Handle the data received after successful authorization:
    • Use userIdentifier for uniquely identifying the Apple user.
    • fullName and email are only available on the first login for this user and your app. Save them.
    • Send userIdentifier, identityToken (contains information for server verification), and authorizationCode to your server for verification and account creation/linking.
    • The server should verify the identityToken with Apple to confirm the authenticity of the request.

In addition to primary authorization, it is also important to implement:

  • Handling user authorization state (e.g., via ASAuthorizationAppleIDProvider().getCredentialState).
  • Ability for the user to revoke authorization.
  • Interaction with your backend to create/authenticate the user after successful Apple authorization.

Note: Sign In with Apple is only available on devices with iOS 13 / macOS Catalina and newer. For older OS versions, a fallback authentication mechanism is required.