Exemplo n.º 1
0
        public void DidComplete(ASAuthorizationController _, ASAuthorization auth)
        {
            var cred = auth.GetCredential <ASAuthorizationAppleIdCredential>();

            var userIdentifier = cred.User;
            var fullName       = cred.FullName;
            var email          = cred.Email;
            var identityToken  = cred.IdentityToken;
            var authCode       = cred.AuthorizationCode;

            // send details to the server

            View.FillWith(new UITextView
            {
                Text =
                    $"\r\n\r\nUser Identifier\r\n {userIdentifier}\r\n\r\n" +
                    $"Full Name\r\n{fullName.GivenName} {fullName.FamilyName}\r\n\r\n" +
                    $"Email\r\n{email}\r\n\r\n" +
                    $"IdentityToken\r\n{identityToken.ToString().Substring(0, 200)}\r\n\r\n" +
                    $"AuthCode\r\n{authCode.ToString().Substring(0, 40)}",

                TextAlignment = UITextAlignment.Center,
                Font          = UIFont.GetMonospacedSystemFont(16, UIFontWeight.Regular),
            }, 40, 50);
        }
        public async Task <AppleAccount> SignInAsync()
        {
            var appleIdProvider = new ASAuthorizationAppleIdProvider();
            var request         = appleIdProvider.CreateRequest();

            request.RequestedScopes = new[] { ASAuthorizationScope.Email, ASAuthorizationScope.FullName };

            var authorizationController = new ASAuthorizationController(new[] { request });

            authorizationController.Delegate = this;
            authorizationController.PresentationContextProvider = this;
            authorizationController.PerformRequests();

            tcsCredential = new TaskCompletionSource <ASAuthorizationAppleIdCredential>();

            var creds = await tcsCredential.Task;

            if (creds == null)
            {
                return(null);
            }

            var appleAccount = new AppleAccount();

            appleAccount.Token          = new NSString(creds.IdentityToken, NSStringEncoding.UTF8).ToString();
            appleAccount.Email          = creds.Email;
            appleAccount.UserId         = creds.User;
            appleAccount.Name           = NSPersonNameComponentsFormatter.GetLocalizedString(creds.FullName, NSPersonNameComponentsFormatterStyle.Default, NSPersonNameComponentsFormatterOptions.Phonetic);
            appleAccount.RealUserStatus = creds.RealUserStatus.ToString();

            return(appleAccount);
        }
        public async Task <(string IdToken, string RawNonce)> GetCredentialAsync()
        {
            if (!Version.TryParse(UIDevice.CurrentDevice.SystemVersion, out var version) || version.Major < 13)
            {
                return(null, null);
            }

            var provider = new ASAuthorizationAppleIdProvider();

            var nonce = GenerateNonce(32);

            var request = provider.CreateRequest();

            request.RequestedScopes = new[] { ASAuthorizationScope.FullName, ASAuthorizationScope.Email };
            request.Nonce           = GetHashedNonce(nonce);

            var controller = new ASAuthorizationController(new[] { request });

            var authorizationControllerDelegate = new AuthorizationControllerDelegate(UIApplication.SharedApplication.KeyWindow);

            controller.Delegate = authorizationControllerDelegate;
            controller.PresentationContextProvider = authorizationControllerDelegate;

            controller.PerformRequests();

            var credential = await authorizationControllerDelegate.GetCredentialAsync().ConfigureAwait(false);

            var idToken = new NSString(credential.IdentityToken, NSStringEncoding.UTF8).ToString();

            return(idToken, nonce);
        }
Exemplo n.º 4
0
 public void DidComplete(ASAuthorizationController controller, ASAuthorization authorization)
 {
     // Determine whether the user authenticated via Apple ID or a stored iCloud password.
     if (authorization.GetCredential <ASAuthorizationAppleIdCredential>() is { } appleIdCredential)
     {
         CompletedWithAppleId?.Invoke(controller, appleIdCredential);
     }
Exemplo n.º 5
0
        public void SignIn(
            bool needEmail    = true,
            bool needFullName = true)
        {
            var requestedScopes = new List <ASAuthorizationScope>();

            if (needEmail)
            {
                requestedScopes.Add(ASAuthorizationScope.Email);
            }
            if (needFullName)
            {
                requestedScopes.Add(ASAuthorizationScope.FullName);
            }

            var request = _appleIdProvider.CreateRequest();

            request.RequestedScopes = requestedScopes.ToArray();

            // Prepare request for Apple ID.
            ASAuthorizationRequest[] requests =
            {
                _appleIdProvider.CreateRequest()
            };

            // Create an authorization controller with the given requests.
            var authorizationController = new ASAuthorizationController(requests)
            {
                Delegate = _authControllerDelegate,
                PresentationContextProvider = _presentationProvider
            };

            authorizationController.PerformRequests();
        }
        static async Task <WebAuthenticatorResult> PlatformAuthenticateAsync(Options options)
        {
            if (DeviceInfo.Version.Major < 13)
            {
                throw new FeatureNotSupportedException();
            }

            var provider = new ASAuthorizationAppleIdProvider();
            var req      = provider.CreateRequest();

            authManager = new AuthManager(Platform.GetCurrentWindow());

            var scopes = new List <ASAuthorizationScope>();

            if (options.IncludeFullNameScope)
            {
                scopes.Add(ASAuthorizationScope.FullName);
            }
            if (options.IncludeEmailScope)
            {
                scopes.Add(ASAuthorizationScope.Email);
            }

            req.RequestedScopes = scopes.ToArray();
            var controller = new ASAuthorizationController(new[] { req });

            controller.Delegate = authManager;
            controller.PresentationContextProvider = authManager;

            controller.PerformRequests();

            var creds = await authManager.GetCredentialsAsync();

            if (creds == null)
            {
                return(null);
            }

            var idToken  = new NSString(creds.IdentityToken, NSStringEncoding.UTF8).ToString();
            var authCode = new NSString(creds.AuthorizationCode, NSStringEncoding.UTF8).ToString();
            var name     = NSPersonNameComponentsFormatter.GetLocalizedString(creds.FullName, NSPersonNameComponentsFormatterStyle.Default, 0);

            var appleAccount = new WebAuthenticatorResult();

            appleAccount.Properties.Add("id_token", idToken);
            appleAccount.Properties.Add("authorization_code", authCode);
            appleAccount.Properties.Add("state", creds.State);
            appleAccount.Properties.Add("email", creds.Email);
            appleAccount.Properties.Add("user_id", creds.User);
            appleAccount.Properties.Add("name", name);
            appleAccount.Properties.Add("realuserstatus", creds.RealUserStatus.ToString());

            return(appleAccount);
        }
Exemplo n.º 7
0
        private void HandleAuthorizationAppleIDButtonPress(object sender, EventArgs e)
        {
            var appleIdProvider = new ASAuthorizationAppleIdProvider();
            var request         = appleIdProvider.CreateRequest();

            request.RequestedScopes = new [] { ASAuthorizationScope.Email, ASAuthorizationScope.FullName };

            var authorizationController = new ASAuthorizationController(new [] { request });

            authorizationController.Delegate = this;
            authorizationController.PresentationContextProvider = this;
            authorizationController.PerformRequests();
        }
        public void DidComplete(ASAuthorizationController controller, ASAuthorization authorization)
        {
            var credential = authorization.GetCredential <ASAuthorizationAppleIdCredential>();

            if (credential != null && !string.IsNullOrEmpty(currentNonce))
            {
                appleToken = credential.IdentityToken.ToString();
                var firebaseCredential = OAuthProvider.GetCredentialWithRawNonce("apple.com", credential.IdentityToken.ToString(), currentNonce);
                Auth.DefaultInstance.SignInWithCredential(firebaseCredential, SignInOnCompletion);
            }
            else
            {
                appleToken = string.Empty;
                SetVerificationStatus(VerificationStatus.Failed, "Sign in failed");
            }
        }
Exemplo n.º 9
0
        // Prompts the user if an existing iCloud Keychain credential or Apple ID credential is found.
        void PerformExistingAccountSetupFlows()
        {
            // Prepare requests for both Apple ID and password providers.
            ASAuthorizationRequest [] requests =
            {
                new ASAuthorizationAppleIdProvider().CreateRequest(),
                new ASAuthorizationPasswordProvider().CreateRequest()
            };

            // Create an authorization controller with the given requests.
            var authorizationController = new ASAuthorizationController(requests);

            authorizationController.Delegate = this;
            authorizationController.PresentationContextProvider = this;
            authorizationController.PerformRequests();
        }
Exemplo n.º 10
0
        public void DidComplete(ASAuthorizationController controller, ASAuthorization authorization)
        {
            if (authorization.GetCredential <ASAuthorizationAppleIdCredential> () is ASAuthorizationAppleIdCredential appleIdCredential)
            {
                var userIdentifier = appleIdCredential.User;
                var fullName       = appleIdCredential.FullName;
                var email          = appleIdCredential.Email;

                // Create an account in your system.
                // For the purpose of this demo app, store the userIdentifier in the keychain.
                try {
                    new KeychainItem("com.xamarin.AddingTheSignInWithAppleFlowToYourApp", "userIdentifier").SaveItem(userIdentifier);
                } catch (Exception) {
                    Console.WriteLine("Unable to save userIdentifier to keychain.");
                }

                // For the purpose of this demo app, show the Apple ID credential information in the ResultViewController.
                if (!(PresentingViewController is ResultViewController viewController))
                {
                    return;
                }

                InvokeOnMainThread(() => {
                    viewController.UserIdentifierText = userIdentifier;
                    viewController.GivenNameText      = fullName?.GivenName ?? "";
                    viewController.FamilyNameText     = fullName?.FamilyName ?? "";
                    viewController.EmailText          = email ?? "";

                    DismissViewController(true, null);
                });
            }
            else if (authorization.GetCredential <ASPasswordCredential> () is ASPasswordCredential passwordCredential)
            {
                // Sign in using an existing iCloud Keychain credential.
                var username = passwordCredential.User;
                var password = passwordCredential.Password;

                // For the purpose of this demo app, show the password credential as an alert.
                InvokeOnMainThread(() => {
                    var message         = $"The app has received your selected credential from the keychain. \n\n Username: {username}\n Password: {password}";
                    var alertController = UIAlertController.Create("Keychain Credential Received", message, UIAlertControllerStyle.Alert);
                    alertController.AddAction(UIAlertAction.Create("Dismiss", UIAlertActionStyle.Cancel, null));

                    PresentViewController(alertController, true, null);
                });
            }
        }
Exemplo n.º 11
0
        private void SignInWithAppl()
        {
            var provider = new ASAuthorizationAppleIdProvider();
            var request  = provider.CreateRequest();

            request.RequestedScopes = new[]
            {
                ASAuthorizationScope.Email,
                ASAuthorizationScope.FullName
            };

            var authorizationController =
                new ASAuthorizationController(new[] { request })
            {
                Delegate = this,
                PresentationContextProvider = this
            };

            authorizationController.PerformRequests();
        }
Exemplo n.º 12
0
        public async Task <AppleAccount> SignInAsync()
        {
            // Fallback to web for older iOS versions
            if (!Is13)
            {
                return(await webSignInService.SignInAsync());
            }

            AppleAccount appleAccount = default;

#if __IOS__13
            var provider = new ASAuthorizationAppleIdProvider();
            var req      = provider.CreateRequest();

            authManager = new AuthManager(UIApplication.SharedApplication.KeyWindow);

            req.RequestedScopes = new[] { ASAuthorizationScope.FullName, ASAuthorizationScope.Email };
            var controller = new ASAuthorizationController(new[] { req });

            controller.Delegate = authManager;
            controller.PresentationContextProvider = authManager;

            controller.PerformRequests();

            var creds = await authManager.Credentials;

            if (creds == null)
            {
                return(null);
            }

            appleAccount                = new AppleAccount();
            appleAccount.IdToken        = JwtToken.Decode(new NSString(creds.IdentityToken, NSStringEncoding.UTF8).ToString());
            appleAccount.Email          = creds.Email;
            appleAccount.UserId         = creds.User;
            appleAccount.Name           = NSPersonNameComponentsFormatter.GetLocalizedString(creds.FullName, NSPersonNameComponentsFormatterStyle.Default, NSPersonNameComponentsFormatterOptions.Phonetic);
            appleAccount.RealUserStatus = creds.RealUserStatus.ToString();
#endif

            return(appleAccount);
        }
        public void SignIn(AuthType type)
        {
            authType = type;

            switch (authType)
            {
            case AuthType.Google:
                GoogleSignIn.SharedInstance.SignInUser();
                SetVerificationStatus(VerificationStatus.Initialized);
                break;

            case AuthType.Facebook:
                if (loginManager != null)
                {
                    loginManager.LogIn(readPermissions.ToArray(), GetTopViewController(), HandleLogin);
                    SetVerificationStatus(VerificationStatus.Initialized);
                }
                break;

            case AuthType.Apple:
                if (IsVersion13)
                {
                    currentNonce = RandomNonceString();
                    var appleIdProvider = new ASAuthorizationAppleIdProvider();
                    var request         = appleIdProvider.CreateRequest();
                    request.RequestedScopes = new[] { ASAuthorizationScope.Email, ASAuthorizationScope.FullName };

                    var authorizationController = new ASAuthorizationController(new[] { request })
                    {
                        Delegate = this,
                        PresentationContextProvider = this
                    };
                    authorizationController.PerformRequests();
                }
                break;
            }
        }
 public void DidComplete(ASAuthorizationController controller, NSError error)
 {
     // Handle error
     tcsCredential?.TrySetResult(null);
     Console.WriteLine(error);
 }
 public override void DidComplete(ASAuthorizationController controller, ASAuthorization authorization)
 {
     _tcs.TrySetResult(authorization.GetCredential <ASAuthorizationAppleIdCredential>());
 }
 public override void DidComplete(ASAuthorizationController controller, NSError error)
 {
     _tcs.TrySetException(new NSErrorException(error));
 }
Exemplo n.º 17
0
 public UIWindow GetPresentationAnchor(ASAuthorizationController controller)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 18
0
 public void DidComplete(ASAuthorizationController controller, NSError error)
 {
     Debug.WriteLine(error.Description);
 }
 public UIWindow GetPresentationAnchor(ASAuthorizationController controller)
 {
     return(_presentationAnchor);
 }
Exemplo n.º 20
0
        public void DidComplete(ASAuthorizationController controller, ASAuthorization authorization)
        {
            var creds = authorization.GetCredential <ASAuthorizationAppleIdCredential>();

            tcsCredential?.TrySetResult(creds);
        }
 public void DidComplete(ASAuthorizationController controller, NSError error)
 {
     SetVerificationStatus(VerificationStatus.Failed, error.LocalizedDescription);
 }
 public UIWindow GetPresentationAnchor(ASAuthorizationController controller)
 {
     return(UIApplication.SharedApplication.KeyWindow);
 }
Exemplo n.º 23
0
 public UIWindow GetPresentationAnchor(ASAuthorizationController controller)
 {
     return(this.View.Window);
 }
Exemplo n.º 24
0
 public void DidComplete(ASAuthorizationController controller, NSError error)
 => tcsCredential?.TrySetException(new Exception(error.LocalizedDescription));
Exemplo n.º 25
0
 public void DidComplete(ASAuthorizationController controller, NSError error)
 {
     Console.WriteLine(error);
 }
Exemplo n.º 26
0
 public UIWindow GetPresentationAnchor(ASAuthorizationController controller)
 => presentingAnchor;
Exemplo n.º 27
0
 public UIWindow GetPresentationAnchor(ASAuthorizationController controller) => View.Window;