apple-signin-unity

repository·master·Indexed 20 days ago

https://github.com/lupidan/apple-signin-unity

A Unity plugin (com.lupidan.apple-signin-unity) that provides a bridge to Apple's native 'Sign in with Apple' functionality. It supports iOS, macOS, tvOS, and visionOS, allowing developers to request email and full name, check credential status, use Quick Login, and handle security via Nonce and State. The plugin includes automated Xcode setup via PostBuild scripts to manage entitlements.

Tokens
9.8K
Snippets
21
Records
34
Agent score
73%

What's inside apple-signin-unity

  1. Overview of Sign in with Apple Unity Plugin

    master

    The Sign in with Apple Unity Plugin allows Unity 3D developers to integrate Apple's native 'Sign in with Apple' feature into their applications. This is often a mandatory requirement for App Store approval if your app uses any other third-party sign-in methods (e.g., Facebook or Google).

    Supported Platforms:

    • iOS
    • macOS: Intel x86_64 and Apple Silicon arm64 (Experimental)
    • tvOS (Experimental)
    • visionOS (Experimental)
  2. How to handle callbacks safely with AppleAuthManager

    master

    The plugin does not use UnitySendMessage. Instead, it uses callbacks in a static context with request identifiers using JSON strings.

    Because callbacks from the iOS SDK are executed on a thread outside of Unity's engine control, you must call Update() on your AppleAuthManager instance regularly (e.g., within a MonoBehaviour.Update() method). This ensures that callbacks are scheduled and executed within Unity's main thread, allowing you to safely update the UI and preventing crashes caused by exceptions thrown during the callback.

  3. Verifying users on iOS vs Server

    master

    Apple's security model distinguishes between device-side checks and server-side verification:

    • On iOS: The initial login provides an Apple User ID and an Authorization Code. For all subsequent checks to see if a user is still valid on the device, use GetCredentialState with that Apple User ID.
    • On the Server: Use the Authorization Code received from the initial iOS login to obtain a refresh token. The server should use this token to verify the user and refresh it periodically (e.g., once a day).
  4. Use Nonce and State in authorization requests

    master

    Both LoginWithAppleId and QuickLogin support optional Nonce and State parameters via their respective argument classes (AppleAuthLoginArgs and AppleAuthQuickLoginArgs).

    • Nonce: A random string that is embedded in the IdentityToken. It is highly recommended to generate a new random Nonce for every request to prevent replay attacks. This is required for integrations with services like Firebase.
    • State: A string that is returned in the received Apple ID credential. It allows you to validate that the response was generated by a request from your specific device.
    // Your custom Nonce and State strings
    var yourCustomNonce = "RANDOM_NONCE_FOR_THE_AUTHORIZATION_REQUEST";
    var yourCustomState = "RANDOM_STATE_FOR_THE_AUTHORIZATION_REQUEST";
    
    // Arguments for a normal Sign In With Apple Request
    var loginArgs = new AppleAuthLoginArgs(
        LoginOptions.IncludeEmail | LoginOptions.IncludeFullName,
        yourCustomNonce,
        yourCustomState);
    
    // Arguments for a Quick Login
    var quickLoginArgs = new AppleAuthQuickLoginArgs(yourCustomNonce, yourCustomState);
  5. Key features of the plugin

    master

    The plugin provides a native implementation of Sign in with Apple with the following capabilities:

    • Customizable Scopes: Request Email and Full name.
    • Credential Status: Check if a user is Authorized, Revoked, or Not Found.
    • Quick Login: Supports rapid authentication, including iTunes Keychain credentials.
    • Automated Xcode Setup: Can programmatically add the 'Sign In with Apple' capability to your Xcode project using a PostBuild script.
    • Notifications: Listen for Credentials Revoked notifications.
    • Security: Support for custom Nonce and State in authorization requests.
    • Error Handling: Includes NSError mapping to ensure detailed error reporting.
    • Data Handling: Supports NSPersonNameComponents for various name styles and customizable serialization.
  6. Configure iOS/tvOS entitlements programmatically

    master

    The recommended way to set up Apple Sign In entitlements for iOS and tvOS is using a Post Process build script. The plugin provides an extension method for Unity's ProjectCapabilityManager called AddSignInWithAppleWithCompatibility which automatically adds the necessary entitlements to your Xcode project after the build finishes.

    This approach is preferred because manual setup is lost if you overwrite your Xcode project during subsequent Unity builds.

    using AppleAuth.Editor;
    
    public static class SignInWithApplePostprocessor
    {
        [PostProcessBuild(1)]
        public static void OnPostProcessBuild(BuildTarget target, string path)
        {
            if (target != BuildTarget.iOS)
                return;
    
            var projectPath = PBXProject.GetPBXProjectPath(path);
            var project = new PBXProject();
            project.ReadFromString(System.IO.File.ReadAllText(projectPath));
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", null, project.GetUnityMainTargetGuid());
            manager.AddSignInWithAppleWithCompatibility();
            manager.WriteToFile();
        }
    }
  7. Initialize AppleAuthManager

    master

    To use the plugin, you must initialize the AppleAuthManager and call its Update() method within the Unity execution loop. This ensures that pending callbacks from the native side are executed correctly.

    1. Check AppleAuthManager.IsCurrentPlatformSupported to ensure the device supports Sign in with Apple.
    2. Create a PayloadDeserializer to handle JSON responses.
    3. Instantiate AppleAuthManager with the deserializer.
    4. Call appleAuthManager.Update() in your Update() loop.
    private IAppleAuthManager appleAuthManager;
    
    void Start()
    {
        if (AppleAuthManager.IsCurrentPlatformSupported)
        {
            var deserializer = new PayloadDeserializer();
            this.appleAuthManager = new AppleAuthManager(deserializer);
        }
    }
    
    void Update()
    {
        if (this.appleAuthManager != null)
        {
            this.appleAuthManager.Update();
        }
    }
  8. Configure visionOS entitlements

    master

    The setup for visionOS is identical to iOS/tvOS, but you must adjust your Post Process build script to target the correct Xcode project filename. Unity exports visionOS projects using Unity-VisionOS.xcodeproj instead of Unity-iPhone.xcodeproj.

    if (target == BuildTarget.VisionOS)
    {
        projectPath = projectPath.Replace("Unity-iPhone.xcodeproj", "Unity-VisionOS.xcodeproj");
    }
  9. Configure macOS entitlements and bundle identifier

    master

    For macOS, the plugin uses a precompiled .bundle file (supporting x86_64 and arm64). To avoid issues when uploading to the Mac App Store, the bundle identifier must be modified to match your project's application identifier.

    Use the AppleAuthMacosPostprocessorHelper.FixManagerBundleIdentifier method within a Post Process build script to automate this.

    Note: Your app must be correctly codesigned with the required entitlements for this feature to work on macOS.

    using AppleAuth.Editor;
    
    public static class SignInWithApplePostprocessor
    {
        [PostProcessBuild(1)]
        public static void OnPostProcessBuild(BuildTarget target, string path)
        {
            if (target != BuildTarget.StandaloneOSX)
                return;
    
            AppleAuthMacosPostprocessorHelper.FixManagerBundleIdentifier(target, path);
        }
    }
  10. Integrate Sign in with Apple with Firebase

    master

    To use Firebase Authentication with the Sign in with Apple Unity Plugin, you must implement a nonce-based authentication flow. This involves generating a cryptographically secure random string (the rawNonce) to send to Firebase, and a SHA256 hash of that string (the nonce) to send to Apple. This ensures the credentials received from Apple are valid and tied to your specific authentication request.

    Prerequisites

    1. Add Firebase to Unity: Follow the official Firebase Unity setup guide.
    2. Configure Firebase for Apple: Follow the Firebase guide for Sign in with Apple.
    3. Install the Plugin: Ensure the apple-signin-unity plugin is installed in your project.
  11. Install the plugin via Unity Package Manager (Git URL)

    master

    For Unity projects version 2020.3 or newer, you can install the plugin by adding the dependency directly to your Packages/manifest.json file.

    "dependencies": {
        "com.lupidan.apple-signin-unity": "https://github.com/lupidan/apple-signin-unity.git?path=Source#1.5.0"
    }