Giter Club home page Giter Club logo

apple-signin-unity's Introduction

Sign in With AppleUnity 3D

Sign in with Apple Unity Plugin

by Daniel Lupiañez Casares

Sponsor

Release License CHANGELOG

openupm

Stars Followers

Screenshot1 Screenshot1 Screenshot2

Overview

Sign in with Apple plugin to use with Unity 3D game engine.

This plugin supports the following platforms:

  • iOS
  • macOS Intel x86_64 AND Apple Silicon arm64(Experimental) (NOTES)
  • tvOS (Experimental)

The main purpose for this plugin is to expose Apple's newest feature, Sign in with Apple, to the Unity game engine.

On WWDC19, Apple announced Sign in with Apple, and on top of that, they announced that every iOS/tvOS/macOS Application that used any kind of Third party sign-ins (like Sign in with Facebook, or Sign in with Google), will have to support Sign in with Apple in order to get approved for the App Store, making it mandatory.

Features

Native Sign in with Apple

  • Support for iOS

  • Support for macOS: Intel x86_64 AND Apple Silicon arm64(Experimental) (NOTES)

  • Support for tvOS (Experimental)

  • Supports Sign in with Apple, with customizable scopes (Email and Full name).

  • Supports Get Credential status (Authorized, Revoked and Not Found).

  • Supports Quick login (including iTunes Keychain credentials).

  • Supports adding Sign In with Apple capability to Xcode project programatically in a PostBuild script.

  • Supports listening to Credentials Revoked notifications.

  • Supports setting custom Nonce and State for authorization requests when Signing In, and attempting a Quick Login.

  • NSError mapping so no details are missing.

  • NSPersonNameComponents support (for ALL different styles).

  • Customizable serialization (uses Unity default serialization, but you can add your own implementation)

Installation

Current stable version is v1.4.3

There are two options available to install this plugin. Either using the Unity Package Manager, or the traditional .unitypackage file.

Unity Package Manager

Install via Git URL

Available starting from Unity 2018.3.

Just add this line to the Packages/manifest.json file of your Unity Project:

"dependencies": {
    "com.lupidan.apple-signin-unity": "https://github.com/lupidan/apple-signin-unity.git#v1.4.3",
}

Install via OpenUPM

The package is available on the openupm registry. You can install it via openupm-cli.

openupm add com.lupidan.apple-signin-unity

Unity Package File

  1. Download the most recent Unity package release here
  2. Import the downloaded Unity package in your app. There are two main folders:
  • The AppleAuth folder contains the main plugin.
  • The AppleAuthSample folder contains sample code to use as a reference, or to test the plugin.

Import detail

Plugin setup (iOS/tvOS)

To be able to use Apple's platform and framework for Authenticating with an Apple ID, we need to set up our Xcode project. Two different options are available to set up the entitlements required to enable Apple ID authentication with the iOS SDK.

Programmatic setup with a Script

RECOMMENDED

This plugin provides an extension method for ProjectCapabilityManager (docs), used to add this entitlement programatically after an Xcode build has finished.

Simply create a Post Processing build script (more info) that performs the call. If you already have a post process build script, it should be simple to add to your code.

The provided extension method is AddSignInWithAppleWithCompatibility. It accepts an optional argument for Unity 2019.3 to indicate the UnityFramework target Guid.

Sample code:

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);
        
        // Adds entitlement depending on the Unity version used
#if UNITY_2019_3_OR_NEWER
            var project = new PBXProject();
            project.ReadFromString(System.IO.File.ReadAllText(projectPath));
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", null, project.GetUnityMainTargetGuid());
            manager.AddSignInWithAppleWithCompatibility(project.GetUnityFrameworkTargetGuid());
            manager.WriteToFile();
#else
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", PBXProject.GetUnityTargetName());
            manager.AddSignInWithAppleWithCompatibility();
            manager.WriteToFile();
#endif
    }
}

Manual entitlements setup

The other option is to manually setup all the entitlements in our Xcode project. Note that when making an iOS Build from Unity into the same folder, if you choose the option to overwrite, you will need to perform the Manual setup again.

  1. In your generated Xcode project. Select the main app Unity-iPhone target and select the option Signing And Capabilities. You should see there an option to add a capability from a list. Just locate Sign In With Apple and add it to your project.

Add Entitlements

  1. This should have added an Entitlements file to your project. Locate it on the project explorer (it should be a file with the extension .entitlements). Inside it you should see an entry like this one:

  1. You need to import the AuthenticationServices.framework library in the Build Phases->Link Binary with Libraries. If you are targeting older iOS versions, mark the library as Optional.

    For Unity 2019.3 onwards, add it to the UnityFramework target

    For previous Unity versions, add it to the main Unity-iPhone target

Add Framework 2019.3 Add Framework Previous versions

Enabling Apple capability

You will also need to setup everything in the Apple's developer portal. More information can be found here. Please remember this plugin only supports native Sign In With Apple on iOS (no REST API support).

There is also a Getting Started site.

Final notes regarding setup

The AuthenticationServices.framework should be added as Optional, to support previous iOS versions, avoiding crashes at startup.

The provided extension method uses reflection to integrate with the current tools Unity provides. It has been tested with Unity 2018.x and 2019.x. But if it fails on your particular Unity version, feel free to open a issue, specifying the Unity version.

Plugin setup (macOS)

An unsigned precompiled .bundle file is available. The precompiled .bundle should support both architectures: Intel x86_64 & Apple Silicon arm64(Experimental). The bundle should be automatically included in your macOS builds. However that .bundle needs to be modified to avoid issues when uploading it to the MacOS App Store.

In particular, the bundle identifier of that .bundle needs to be modified to a custom one.

To automate the process, there is a helper method that will change the bundle identifier to one based on your project's application identifier. You should call this method on a Postprocess build script of your choice.

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);
    }
}

The Xcode project with the source code to generate a new bundle file is available at MacOSAppleAuthManager/MacOSAppleAuthManager.xcodeproj

To support the feature, the app needs to be codesigned correctly, including the required entitlements. For more information regarding macOS codesign, please follow this link.

Implement Sign in With Apple

Currently, it seems Sign In With Apple does not work properly in the simulator. This needs testing on a device with an iOS 13 version.

An overall flow of how the native Sign In With Apple flow could work is presented in this diagram.

Frameworks detail

Initializing

private IAppleAuthManager appleAuthManager;

void Start()
{
    ...
   // If the current platform is supported
   if (AppleAuthManager.IsCurrentPlatformSupported)
   {
       // Creates a default JSON deserializer, to transform JSON Native responses to C# instances
       var deserializer = new PayloadDeserializer();
       // Creates an Apple Authentication manager with the deserializer
       this.appleAuthManager = new AppleAuthManager(deserializer);    
   }
    ...
}

void Update()
{
    ...
    // Updates the AppleAuthManager instance to execute
    // pending callbacks inside Unity's execution loop
    if (this.appleAuthManager != null)
    {
        this.appleAuthManager.Update();
    }
    ...
}

Perform Sign In With Apple

⚠️ You will receive users's email and name ONLY THE FIRST TIME THE USER LOGINS. Any further login attempts will have a NULL Email and FullName, unless you revoke the credentials

If you want to Sign In and request the Email and Full Name for a user, you can do it like this:

var loginArgs = new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName);

this.appleAuthManager.LoginWithAppleId(
    loginArgs,
    credential =>
    {
        // Obtained credential, cast it to IAppleIDCredential
        var appleIdCredential = credential as IAppleIDCredential;
        if (appleIdCredential != null)
        {
            // Apple User ID
            // You should save the user ID somewhere in the device
            var userId = appleIdCredential.User;
            PlayerPrefs.SetString(AppleUserIdKey, userId);

            // Email (Received ONLY in the first login)
            var email = appleIdCredential.Email;

            // Full name (Received ONLY in the first login)
            var fullName = appleIdCredential.FullName;

            // Identity token
            var identityToken = Encoding.UTF8.GetString(
                appleIdCredential.IdentityToken,
                0,
                appleIdCredential.IdentityToken.Length);

            // Authorization code
            var authorizationCode = Encoding.UTF8.GetString(
                appleIdCredential.AuthorizationCode,
                0,
                appleIdCredential.AuthorizationCode.Length);

            // And now you have all the information to create/login a user in your system
        }
    },
    error =>
    {
        // Something went wrong
        var authorizationErrorCode = error.GetAuthorizationErrorCode();
    });

Quick login

This should be the first thing to try when the user first runs the application.

If the user has previously authorized the app to login with Apple, this will open a native dialog to re-confirm the login, and obtain an Apple User ID.

If the credentials were never given, or they were revoked, the Quick login will fail.

Frameworks detail

var quickLoginArgs = new AppleAuthQuickLoginArgs();

this.appleAuthManager.QuickLogin(
    quickLoginArgs,
    credential =>
    {
        // Received a valid credential!
        // Try casting to IAppleIDCredential or IPasswordCredential

        // Previous Apple sign in credential
        var appleIdCredential = credential as IAppleIDCredential; 

        // Saved Keychain credential (read about Keychain Items)
        var passwordCredential = credential as IPasswordCredential;
    },
    error =>
    {
        // Quick login failed. The user has never used Sign in With Apple on your app. Go to login screen
    });

Note that, if this succeeds, you will ONLY receive the Apple User ID (no email or name, even if it was previously requested).

IOS Keychain Support

When performing a quick login, if the SDK detects IOS Keychain credentials for your app, it will return those.

Just cast the credential to IPasswordCredential to get the login details for the user.

Checking credential status

This is used to verify that an Apple User ID is still valid.

Given an userId from a previous successful sign in. You can check the credential state of that user ID like so:

this.appleAuthManager.GetCredentialState(
    userId,
    state =>
    {
        switch (state)
        {
            case CredentialState.Authorized:
                // User ID is still valid. Login the user.
                break;
            
            case CredentialState.Revoked:
                // User ID was revoked. Go to login screen.
                break;
            
            case CredentialState.NotFound:
                // User ID was not found. Go to login screen.
                break;
        }
    },
    error =>
    {
        // Something went wrong
    });

Listening to credentials revoked notification

It may be that your user suddenly decides to revoke the authorization that was given previously. You should be able to listen to the incoming notification by registering a callback for it.

this.appleAuthManager.SetCredentialsRevokedCallback(result =>
{
    // Sign in with Apple Credentials were revoked.
    // Discard credentials/user id and go to login screen.
});

To clear the callback, and stop listening to notifications, simply set it to null

this.appleAuthManager.SetCredentialsRevokedCallback(null);

Nonce and State support for Authorization Requests

Both methods, LoginWithAppleId and QuickLogin, use a custom structure containing arguments for the authorization request.

An optional Nonce and an optional State can be set for both structures when constructing them:

// Your custom Nonce string
var yourCustomNonce = "RANDOM_NONCE_FORTHEAUTHORIZATIONREQUEST";
var yourCustomState = "RANDOM_STATE_FORTHEAUTHORIZATIONREQUEST";

// 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);

The State is returned later in the received Apple ID credential, allowing you to validate that the request was generated in your device.

The Nonce is embedded in the IdentityToken, included in the received Apple ID credential. It is important to generate a new random Nonce for every request. This is useful for services that provide a built in solution for Sign In With Apple, like Firebase

Some tentative guide is available for Firebase integration here

More info about State and Nonce can be found in this WWDC 2020 session (check at 2m35s)

FAQ

Does it support landscape orientations?

On iOS 13.0, Apple does not support landscape orientation for this feature. For more details, check this issue.

How can I Logout? Does the plugin provide any Logout option?

On iOS 13 Apple does not provide any method to "logout" programatically. If you want to "logout" and re-test account creation, you need to revoke the credentials through settings.

Go to Settings => Click your iTunes user => Password & Security => Apple ID logins. There you can select the app and click on Stop using Apple ID.

After this, the credentials are effectively revoked, your app will receive a Credentials Revoked notification. This will allow you to re-test account creation.

I am not getting a full name, or an email, even though I am requesting them in the LoginWithAppleId call

This probably means that you already used Sign In with apple at some point. Apple will give you the email/name ONLY ONCE. Once the credential is created, it's your app/game's responsibility to send that information somewhere, so an account is created with the given user identifier.

If a credential was already created, you will only receive a user identifier, so it will work similarly to a Quick Login.

If you want to test new account scenarios, you need to revoke your app credentials for that Apple ID through the settings menu.

Is it possible to NOT request the user's email or full name?

Yes, just provide LoginOptions.None when calling LoginWithAppleId and the user will not be asked for their email or full name. This will skip that entire login step and make it more smooth. It is recommended if the user's email or full name is not used.

appleAuthManager.LoginWithAppleId(LoginOptions.None, credential => { ... }, error => { ... });

Does the plugin use UnitySendMessage?

No. The plugin uses callbacks in a static context with request identifiers using JSON strings. Callbacks are scheduled inside AppleAuthManager, and calling Update on it will execute those pending callbacks.

Why do I need to call Update manually on the AppleAuthManager instance?

Callbacks from iOS SDK are executed in their own thread (normally the main thread), and outside Unity's engine control. Meaning that you can't update the UI, or worse, if your callback throws an Exception (like a simple NRE), it will crash the Game completely.

It's recommended to update the instance of AppleAuthManager regularly in a MonoBehaviour of your choice.

What deserialization library does it use by default?

If you initialize the AppleAuthManager with the built-in PayloadDeserializer, it uses Unity JSON serialization system, so no extra libraries are added.

You can also implement your own deserialization by implementing an IPayloadDeserializer.

Any way to get a refresh token on iOS to verify a user?

NO, That's not how Apple wants you to do it. This is how they want you to verify a user:

On iOS: The first login gives you the Apple User ID and an Authorization Code to send to your backend. Checking the validity of a user on the device, from now on, should be done with GetCredentialState and that Apple User ID.

On the server: It receives the data from the first login on iOS to create the user. Uses that received Authorization Code to get a refresh token for the user. Refreshes the token once a day. More info here

I am getting a CFBundleIdentifier Collision error when uploading my app to the macOS App Store:

If you are experiencing an error like this when uploading your macOS app to the App Store

The info.plist CFBundleIdentifier value 'com.lupidan.MacOSAppleAuthManager" of 'appname.app/Contents/Plugins/MacOSAppleAuthManager.bundle' is already in use by another application"

It probably means that your postprocess build script for macOS is not setup correctly.

You should call AppleAuthMacosPostprocessorHelper.FixManagerBundleIdentifier to fix the plugin's bundle identifier to a custom one for your app.

You can find more details about the bug here

apple-signin-unity's People

Contributors

alexey-unity avatar channingcorn avatar kezzo avatar lupidan avatar rumaniel avatar sbeca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apple-signin-unity's Issues

Does it work on MacOS?

Before all else let me apologize for asking this question here as it's clearly not an issue, however I couldn't find any info on that and I hesitate to update my project. I'm guessing that because unity doesn't generate an XCode project for Mac. Am I right?

Undefined Symbol: _AppleAuth_

Hi, I'm getting these errors when I'm trying to build the project on xcode after implementing the plugin.

Undefined symbol: _AppleAuth_GetPersonNameUsingFormatter
Undefined symbol: _AppleAuth_LogMessage
Undefined symbol: _AppleAuth_QuickLogin
Undefined symbol: _AppleAuth_RegisterCredentialsRevokedCallbackId
Undefined symbol: _AppleAuth_LoginWithAppleId
Undefined symbol: _AppleAuth_GetCredentialState
Undefined symbol: _AppleAuth_IsCurrentPlatformSupported
Undefined symbol: _AppleAuth_SetupNativeMessageHandlerCallback

Sample Project "Unsupported Platform" on iPhone 6, iOS 11.1.2, Unity version 2018.4.23f1, Jenkins CI Build

Hi, when I build the sample project included within this git repo I get this message
image

In my own test project, when I remove this if statement
image

and run LogInWithAppleId with try catch printing, I get AppleAuth.Native.AppleError on the same iPhone6
[ Initialization was present in code ]

image


Phone used to run the build :
image


The SignInWithApplePostprocessor.cs now works fine with no build errors, and how I'm building it is through Jenkins CI.

Also, the Sign in With Apple for my test app is enabled at the apple developer's identifiers website
here [https://developer.apple.com/account/resources/identifiers/list]

image


I have also double checked that the bundle identifier is the same with the bundle id found in the Apple Developers Identifiers, and also made sure that the UDID is consistent with the devices on the apple developer dashboard

Apps using Apple Id Icon

Hello,

Maybe this is not the correct forum to ask this question. But I do not get my app icon in apple setting view-> in the menu-> Apps using Apple Id. All other icons are visible( including under normal settings) and are set up through unity. Do you have any idea about this? I'm still testing my application only through Test Flight, could this be the reason.

Question: How exactly do we login with the credentials?

Your flow chart shows in 2 situations that if we have credentials we use those to login.

I'm a bit confused by how this happens...

In your sample you have this method:

    private void CheckCredentialStatusForUserId(string appleUserId)
    {
        // If there is an apple ID available, we should check the credential state
        this._appleAuthManager.GetCredentialState(
            appleUserId,
            state =>
            {
                switch (state)
                {
                    // If it's authorized, login with that user id
                    case CredentialState.Authorized:
                        this.SetupGameMenu(appleUserId, null);
                        return;
                    
                    // If it was revoked, or not found, we need a new sign in with apple attempt
                    // Discard previous apple user id
                    case CredentialState.Revoked:
                    case CredentialState.NotFound:
                        this.SetupLoginMenuForSignInWithApple();
                        PlayerPrefs.DeleteKey(AppleUserIdKey);
                        return;
                }
            },
            error =>
            {
                var authorizationErrorCode = error.GetAuthorizationErrorCode();
                Debug.LogWarning("Error while trying to get credential state " + authorizationErrorCode.ToString() + " " + error.ToString());
                this.SetupLoginMenuForSignInWithApple();
            });
    }

But I don't actually see how login happens after that...
You call SetupGameMenu which only prints values...

No callback from QuickLogin if user cancels.

Hi lupidan,
Firstly, thanks for the great plugin. We needed SignInWithApple urgently and this plugin is really helping.
In testing though I've found that when I click 'continue' then 'cancel' on the Quick login screen - I get neither the success nor error callback called.
I can see the following in the logs:

AuthKit           Authorization failed: Error Domain=AKAuthenticationError Code=-7003 ...
AuthKitUIService  AKRemoteViewController did complete with authorization (null) (error ... -7003)

... but looking at the code either the success or error callbacks should be called, yet neither is. Do you have any thoughts on this?

my code follows below (sorry if it's a bit messy, it's work in progress):

	public static void AttemptQuickLogin()
	{
		var quickLoginArgs = new AppleAuthQuickLoginArgs();

		_appleAuthManager.QuickLogin(
			quickLoginArgs,
			credential =>
			{
				// Received a valid credential!
				// Try casting to IAppleIDCredential or IPasswordCredential

				// Previous Apple sign in credential
				var appleIdCredential = credential as IAppleIDCredential;
				if (appleIdCredential != null)
				{
					_isSignedInWithApple = true;
					_appleUserId = credential.User;
					PlayerPrefs.SetString(AppleUserIdKey, _appleUserId);
					_pleaseUpdateServer = true;
				}

				// Saved Keychain credential (read about Keychain Items)
				var passwordCredential = credential as IPasswordCredential;
				// ?
				Debug.Log("SignInWithAppleClass: _initComplete = true");
				_initComplete = true;
			},
			error =>
			{
				//var authorizationErrorCode = error.GetAuthorizationErrorCode();
				// Quick login failed. Show login button on settings.
				_isSignedInWithApple = false;
				Debug.Log("SignInWithAppleClass: _initComplete = true");
				_initComplete = true;
			});
	}

Unable to view Username and email

@lupidan Hello. I used your plugin, but I am not able to retreive username and email. It is showing empty input fields, One at one time it showed me the Username and email. I have logout the account from my iPad as well and login again and repeated the same procedure as you have told to do.But still no luck.It showing empty fields. Any guess what to do ?

FirebaseException - The nonce in ID Token does not match

Error
Firebase.FirebaseException: The nonce in ID TOKEN "noncestring" does not match the SHA256 hash of the raw nonce "noncestring" in the request.

I have tried using the same nonce string for Apple login and Firebase oath and also tried SHA256 for Apple login where the error becomes:

Firebase.FirebaseException: The nonce in ID TOKEN "sha256 of noncestring" does not match the SHA256 hash of the raw nonce "noncestring" in the request.

Must AppleAuthManager receive a different form of nonce string?

Relogin works in 1.0.0, but doesn't work in 1.2.0 and 1.3.0

Reloginning doesn't return credentials in version 1.2.0. Is this intended behaviour? I read the answer in README, telling that Apple gives credentials (email and stuff) only once. But the ability to repeatedly get credentials in 1.0.0 really confused me.

How to get expiry of the authToken and a "refresh token"?

First of all, thanks a lot for this package, works like a charm!

I am trying to integrate the apple sign in with a Meteor-based backend, which already has an OAuth-based flow of Sign in with Apple in place. After analyzing its code, I realized that the Meteor flow expects:

  1. The expiry date (timestamp) of the authToken (aka Authorization Code), and
  2. A refresh token, in case the authToken is expired

Both of these are handed over from Apple during OAuth. Is there a chance to these values via the native API as well? I could not find them in the existing C# API.

Authentication Framework Adds as required not optional

Project.AddCapability(TargetGUID, PBXCapabilityType.SignInWithApple, EntitlementFilename);
var ProjectCapabilityManager = new ProjectCapabilityManager(ProjectPath,EntitlementFilename, null, TargetGUID);
ProjectCapabilityManager.AddSignInWithApple();
ProjectCapabilityManager.WriteToFile();

        Project.AddFrameworkToProject(TargetGUID, AuthenticationServicesFramework, true);//true means weak/optional but this adds as required ,which will crash on less than 13 IOS version devices 
        File.WriteAllText(PlistPath, PlistDocument.WriteToString());
        Project.WriteToFile(ProjectPath);

Full name,Email

unity 2017,
ios 13 x
mail and name are definitely not coming

Xcode Build Failed - Library not found for -IFirebaseAuth

Hi! I tried to make an AppleSignin on my unity game, and the user can get authentication into firebase, so I follow your tutorial step by step, I got an error when I built in Xcode, It shows Library not found for -IFirebaseAuth, But I already import firebaseauth package into my unity project, Do I miss something? Please help me with that, Thank you in advance :)
Error

Full name doesn't represent the actual name

Unity 2019.3.15, latest plugin version 1.3.0

On first login attempt full name property is incorrect, seems it's not parsed properly. Here what I get in log:
fullname: AppleAuth.Native.FullPersonName

Using another plugin for test I get a proper name

Is it possible to not get the user's email or full name?

For GDPR and general privacy reasons I would like to set the login scope to not include the user's email or full name.
The LoginOptions enum only allows setting either of them or both, but doesn't included a value to exclude both scopes.
Is this because of how Apple SignIn works or would it be possible to get this implemented into this plugin?

I can't login, Sign Up Not Completed

Hello, thanks your support plugin.

I can't sign in with apple.
here is my work process, what's wrong?

  1. create empty project in unity 2019 4.9f1
  2. import asset by asset store
  3. build xcode project : bundle id is same my game.
  4. xcode play button click, compile and run
  5. I can't sign in : Sign Up Not Completed

please help, Why I can't sign in...
Photo_2020-09-16-11-27-39

AKAuthenticationError Code=-7026

My Apple Sign In is working fine when I run my app by Xcode in development mode.

After I archive a distribution IPA, my co-worker will replace provisioning profile and bundle ID for publishing to TestFlight, and then Apple Sign In can't work anymore but show this error when I try to sign in with Apple.

Authorization failed: Error Domain=AKAuthenticationError Code=-7026 UserInfo={AKClientBundleID=<private>}

I search some articles on Google, all they say is that I probably forgot to add capability, but I actually add the "Sign In with Apple" capability and run it by Xcode successfully.

Is there any possibility that my co-worker's provisioning profile missing settings?(We are cross-country partner so I can't easily check their settings)

Or something should be modified before I archive a distribution IPA?

'PBXProject.GetUnityTargetName()' is obsolete in Unity 2019.3

Getting the following error after updating to Unity 2019.3

Assets/Scripts/Integrations/SignInWithApplePostprocessor.cs(16,94): error CS0619: 'PBXProject.GetUnityTargetName()' is obsolete: 'This function is deprecated. There are two targets now, call GetUnityMainTargetGuid() - for app or GetUnityFrameworkTargetGuid() - for source/plugins to get Guid instead of calling to TargetGuidByName(GetUnityTargetName()).'

AKAuthenticationError Code=-7026 with LoginWithAppleId()

When I try to make a LoginWithAppleId() I get the error: "Authorization failed: AKAuthenticationError Code=-7026 UserInfo={AKClientBundleID=}". I've read it is invoked when you don't add the "Sign in with Apple" capability or if you don't enable it on the Apple developer page, but I did both. I've also tried to configure Xcode with capability and framework with a PostProcess method and manually and I've tried with different Ad Hoc and App Store (using TestFlight) provisioning profiles.
The strange thing is that the sign in works well in the Xcode Simulator and not in iOS 13 devices.

I'm using Unity 2018.4.17f1 with Firebase Authentication.

Linking UNityFramework then error

Hey im trying to build with this plugin but it fails :

8784: ▸ Compiling PersonNameComponentsFormatting.m 8785: ▸ Linking UnityFramework 8786: ▸ ❌; Undefined symbols for architecture arm64 8787: ▸ > Symbol: _OBJC_CLASS_$_ASPasswordCredential 8788: ▸ > Referenced from: objc-class-ref in AppleAuthManager.o 8789: ▸ ❌; ld: symbol(s) not found for architecture arm64 8790: ▸ ❌; clang: error: linker command failed with exit code 1 (use -v to see invocation) 8791: ▸ Linking UnityFramework 8792: ▸ ❌; Undefined symbols for architecture armv7 8793: ▸ > Symbol: _ASAuthorizationScopeEmail 8794: ▸ > Referenced from: -[AppleAuthManager loginWithAppleId:withOptions:andNonce:] in AppleAuthManager.o 8795: ▸ ** ARCHIVE FAILED ** 8796: ▸ The following build commands failed:

Only works the first time

Hi friends, I have tried this great plugin, I install it, configure it and run it. It works great, retreive ID, Name, email, etc., but when I logout and try login again it does not retreive the name nor the email, I tried to uninstall and install again but never retreive all data again.
I did some wrong? I need to do anything else?

Tests

Can I test it in editor?

can i rotate popup?

주석 2019-10-01 161546

orientation of my project is landscape.
Can I rotate popup the same as the project setting?

Error 1000 when trying to login after app close

Hi it seems I got the part working where you press the button and it logs you in initially.
When you restart it shows an error 1000 from Apple which seems to be unknown.
You can still login by pressing the sign in button again though.

I am saving the user and trying the quicklogin or whatever as per README but as I wrote I get the error code 1000.

https://hastebin.com/ranecaruwu.cs

AddSignInWithAppleWithCompatibility missing

I just downloaded the latest version and integrated it in our project for the first time. Following the docs, it seems that AddSignInWithAppleWithCompatibility is missing. Checking the metadata of ProjectCapabilityManager, it only has AddSignInWithApple.
This is in Unity 2019.3.15f

var project = new PBXProject();
project.ReadFromString(System.IO.File.ReadAllText(projectPath));
var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", null, project.GetUnityMainTargetGuid());
manager.AddSignInWithAppleWithCompatibility(project.GetUnityFrameworkTargetGuid());
manager.WriteToFile();

Android

Hi,

sorry, it's more a question/request....
It does not work with Android, right? Because that can be a problem for some multi-platform apps or games.

Thanks for your work!

Using with firebase auth?

Hello,

Im trying to use your plugin with the firebase auth plugin. In order to create a firebase credential I need what they call an idToken as a string and an access token also as a string. Any idea how I could generate these from your plugin? Looking at the IApplIDCredential interface there are byte arrays called IdentityToken and AuthorizationCode, could these be what I need once in string format?

Cheers Macca.

CFBundleIdentifier Collision

Hi there

On MacOSX build after codesigning and I try to upload with Transporter I can't upload it getting Transporter Delivery error

ERROR ITMS-90511 @CFBundleIdentifier Collision. The info.plist CFBundleIdentifier value 'com.lupidan.MacOSAppleAuthManager" of 'appname.app/Contents/Plugins/MacOSAppleAuthManager.bundle' is already in use by another application"

Any ideas how to work around this please?

I had codesigned MacOSAppleAuthManager
codesign -vvv --force --timestamp --options runtime -s "3rd Party Mac Developer Application: Name (code)" "appname.app/Contents/Plugins/MacOSAppleAuthManager.bundle"

Do I need to add any reference to MacOSAppleAuthManager in Info.plist?

Thanks a bunch for your help

Error 1001 - Canceled

I'm having this error when I try to login:

Canceled - The operation couldn't be completed. (com.apple.AuthenticationServices.AuthorizationError error 1001.)

Am I doing something wrong in the Xcode or Itunes Connect?

Ps: The game is not published yet.

FullName is always empty

Hi, everything with this plugin works really well, except the FullName property is empty both in QuickLogin and Login.

LoginOptions.IncludeFullName is set, of course.

Any suggestions?

Also missing a Logout()... :)

Compilation failure during continuous integration Jenkins build for SignInWithAppleProcessor.cs

Hello there, thank you for your github project

I'm using the SignInWithAppleProcessor.cs script and I'm receiving compilation errors when building it using a jenkins continuous integration setup. [Error in second screenshot]

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);
        
        // Adds entitlement depending on the Unity version used
#if UNITY_2019_3_OR_NEWER
            var project = new PBXProject();
            project.ReadFromString(System.IO.File.ReadAllText(projectPath));
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", null, project.GetUnityMainTargetGuid());
            manager.AddSignInWithAppleWithCompatibility(project.GetUnityFrameworkTargetGuid());
            manager.WriteToFile();
#else
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", PBXProject.GetUnityTargetName());
            manager.AddSignInWithAppleWithCompatibility();
            manager.WriteToFile();
#endif
    }

image
Error :

 [Unity] -----CompilerOutput:-stdout--exitcode: 1--compilationhadfailure: True--outfile: Temp/Assembly-CSharp.dll
24: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(2,19): error CS0234: The type or namespace name 'Callbacks' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
25: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(3,19): error CS0234: The type or namespace name 'iOS' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
26: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(4,17): error CS0234: The type or namespace name 'Editor' does not exist in the namespace 'AppleAuth' (are you missing an assembly reference?)
27: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(9,43): error CS0246: The type or namespace name 'BuildTarget' could not be found (are you missing a using directive or an assembly reference?)
28: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(8,6): error CS0246: The type or namespace name 'PostProcessBuildAttribute' could not be found (are you missing a using directive or an assembly reference?)
29: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(8,6): error CS0246: The type or namespace name 'PostProcessBuild' could not be found (are you missing a using directive or an assembly reference?)
30: [Unity] ERROR: Assets/Scripts/SignInWithApplePostProcessor.cs(2,19): error CS0234: The type or namespace name 'Callbacks' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
31: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(2,19): error CS0234: The type or namespace name 'Callbacks' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
32: [Unity] ERROR: Assets/Scripts/SignInWithApplePostProcessor.cs(3,19): error CS0234: The type or namespace name 'iOS' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
33: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(3,19): error CS0234: The type or namespace name 'iOS' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
34: [Unity] ERROR: Assets/Scripts/SignInWithApplePostProcessor.cs(4,17): error CS0234: The type or namespace name 'Editor' does not exist in the namespace 'AppleAuth' (are you missing an assembly reference?)
35: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(4,17): error CS0234: The type or namespace name 'Editor' does not exist in the namespace 'AppleAuth' (are you missing an assembly reference?)
36: [Unity] ERROR: Assets/Scripts/SignInWithApplePostProcessor.cs(9,43): error CS0246: The type or namespace name 'BuildTarget' could not be found (are you missing a using directive or an assembly reference?)
37: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(9,43): error CS0246: The type or namespace name 'BuildTarget' could not be found (are you missing a using directive or an assembly reference?)
38: [Unity] ERROR: Assets/Scripts/SignInWithApplePostProcessor.cs(8,6): error CS0246: The type or namespace name 'PostProcessBuildAttribute' could not be found (are you missing a using directive or an assembly reference?)
39: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(8,6): error CS0246: The type or namespace name 'PostProcessBuildAttribute' could not be found (are you missing a using directive or an assembly reference?)
40: [Unity] ERROR: Assets/Scripts/SignInWithApplePostProcessor.cs(8,6): error CS0246: The type or namespace name 'PostProcessBuild' could not be found (are you missing a using directive or an assembly reference?)
41: [Unity] Assets/Scripts/SignInWithApplePostProcessor.cs(8,6): error CS0246: The type or namespace name 'PostProcessBuild' could not be found (are you missing a using directive or an assembly reference?)

Am I possibly placing this script in the wrong folder.. [It was in the scripts folder] or am I missing a step?

Or maybe the UnityEditor namespace just isn't included when building unity projects through batch scripts [?]

Unity Version : 2018.4.23f1

any way to receive IdentityToken without user operation?

hi, thank you for creating the plugin!! this save my time quite a lot ;D

To gain more security, I want to verify IAppleIDCredential.User with IAppleIDCredential.IdentityToken on server side. without it, modified client can send arbiter account id to server, and may hijack other user's data.

I'm able to do this successfully with great unity example, but it seems that IdentityToken only valid 10min, which means I always require fresh token when user do operation which requires apple account id.

IAppleAuthManager.GetCredentialState does not help because it only returns credential validity, I also try IAppleAuthManager.QuickLogin because it calls AppleAuth_IOS_LoginSilently, which seems to do exact thing I want (guessed from name). but it also ask me to authorize operation with touch ID.

is there any way to receive IdentityToken without user operation? am I missed something to run IAppleAuthManager.QuickLogin correctly?

regards,

How to get nonce?

Hello

I am trying to login to the firebase using credentials.
Code:

var loginArgs = new AppleAuthLoginArgs(AppleAuth.Enums.LoginOptions.IncludeEmail | AppleAuth.Enums.LoginOptions.IncludeFullName);

appleAuthManager.LoginWithAppleId(
loginArgs,
credentials =>
{
var appleIdCredential = credentials as IAppleIDCredential;
if (appleIdCredential == null)
{
return;
}

string rawNonce = loginArgs.Nonce;

string authCode = Encoding.UTF8.GetString(appleIdCredential.AuthorizationCode);

Credential credential = OAuthProvider.GetCredential("apple.com", Encoding.UTF8.GetString(appleIdCredential.IdentityToken), rawNonce, authCode);

auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInWithCredentialAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
return;
}

user = auth.CurrentUser;

Debug.LogFormat("User signed in successfully: {0} ({1})",
user.DisplayName, user.UserId);
});
},
error =>
{
return;
});

Error:

ApplicationException: provider_id && id_token && raw_nonce

I think I am getting wrong rawNonce from the code below.
Please help me to fix this issue.
Thanks.

Unable to sign in on iOS 13.1

Thanks for making this plugin!

It has been working fine when testing on iOS 13, but when trying on iOS 13.1 it gives the error
"Native AppAuth is only available from iOS 13.0"

Pressing "Close" when user is not signed in to settings returns "Unknown" error code

Pressing the "Close" button in the screenshot below returns an "Unknown" AuthorizationErrorCode rather than "Canceled". This happens when the user is not signed in to their Apple ID on phone settings. Is that to be expected?

I see the following error message in the logs:
Authorization failed: Error Domain=AKAuthenticationError Code=-7022 "(null)" UserInfo={AKClientBundleID=...}

IMG_0003

Also, thank you for making this plugin; it's much appreciated!

Email only in first login

Hi there,

We are having an issue getting our app approved by Apple. We have implemented your plugin and it provides the user's email only on the first login, as shown in the example. We are having some issues with account creation and user permissions because we can only fetch the email the first time but as Apple explains in this link, we can get the email any time:

While Apple provides the user’s email address in the identity token on all subsequent API responses, it doesn’t include other information about the user, such as their name. When you receive user information from the API response, immediately store it locally so your app can access it again in the event of a process or network failure.

Is it possible that the plugin has this limitation? If you think it can be fixed by changing some of the native code, I could take a look and submit a pull request when done.

Thanks,

Jay

Unsupported Platform Issue

I implemented the plugin to follow the guideline. but the plugin notified AppleAuthManager.IsCurrentPlatformSupported is false, although I build it on iPad pro with ios 13.

Nonce question

Hi lupidan,

I have a question regarding the nonce token generation and retrival. Due to the implementation of Firebase I have to send the token ID and the raw nonce to be able to authenticate in firebase with Sign in with apple provider.
I can get identity token from your IAppleIDCredential interface under IdentityToken property, but I'm having problems to get the nonce. In the same IAppleIDCredential interface there is a State property that the comment states:

An arbitrary string that your app provided to the request that generated the credential.

I think this is the nonce, but it's always null when I get the credential. There is any way to get the raw nonce token?

Thanks for your great work, It saved us a great deal of time.

Gracias!

dyld: Symbol not found: _MTLHeapDescriptorClass

 I try to build your sample project and I can build without any error until the program starts, the Xcode shows an error

Thank for your great plugin but Am I missing something?

dyld: Symbol not found: _MTLHeapDescriptorClass
Referenced from: /private/var/containers/Bundle/Application/B0273215-7B22-4F1A-9FE6-A2CA022CB61D/testappleauth.app/testappleauth
Expected in: flat namespace
in /private/var/containers/Bundle/Application/B0273215-7B22-4F1A-9FE6-A2CA022CB61D/testappleauth.app/testappleauth
(lldb)

ภาพหน้าจอ 2562-12-10 เวลา 23 59 14

Sign In failure

Got error on authorization.
Authorization failed: Error Domain=AKAuthenticationError Code=-7071 "(null)"
Sign in with Apple failed Unknown AppleAuth.Native.AppleError
<>c:b__11_1(IAppleError)

I've got Sing in with Apple in entitlements and added in capabilities also

App cannot start after signing

Unity 2018.4.12 F1 version. After exporting the Mac version of. App, it can run normally, but after signing, the app can't be opened. What's your wish? In addition, does the plug-in have any requirements for the version of unity?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.