Esempio n. 1
0
        void OnAuth(object sender, EventArgs e)
        {
            string clientId    = null;
            string redirectUri = null;

            switch (Device.RuntimePlatform)
            {
            case Device.iOS:
                clientId    = Constants.ClientIdiOS;
                redirectUri = Constants.RedirectUrliOS;
                break;

            case Device.Android:
                clientId    = Constants.ClientIdAndroid;
                redirectUri = Constants.RedirectUrlAndroid;
                break;
            }

            _oAuth2Authenticator = new OAuth2Authenticator(
                clientId,
                null,
                Constants.Scope,
                new Uri(Constants.AuthorizeUrl),
                new Uri(redirectUri),
                new Uri(Constants.AccessTokeUrl),
                null,
                true);

            _oAuth2Authenticator.Completed   += OnAuthCompleted;
            _oAuth2Authenticator.Error       += OnAuthError;
            AuthenticationState.Authenticator = _oAuth2Authenticator;

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(_oAuth2Authenticator);
        }
        /// <summary> To use this method you need to register the login presenter. Look in the documentation of this method (Right mouse click -> Go to definition)
        /// or visit: https://developer.xamarin.com/guides/xamarin-forms/cloud-services/authentication/oauth/  </summary>
        /// You need to create a OAuthLoginPresenter class in the iOS and Android App and register the presenter after the "global::Xamarin.Forms.Forms.Init();" line
        /// in the AppDelegate of the iOS App and in the MainActivity of the Android App.
        /// --------------------------------------------------------------------------------------------------
        /// iOS OAuthLoginPresenter Class:
        ///  namespace InstagramApp.iOS
        ///  {
        ///    public class OAuthLoginPresenter
        ///        {
        ///           UIViewController rootViewController;
        ///
        ///            public void Login(Authenticator authenticator)
        ///            {
        ///                authenticator.Completed += AuthenticatorCompleted;
        ///
        ///
        ///                rootViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
        ///                rootViewController.PresentViewController((UINavigationController)authenticator.GetUI(), true, null);
        ///            }
        ///
        ///            void AuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
        ///            {
        ///                rootViewController.DismissViewController(true, null);
        ///                ((Authenticator)sender).Completed -= AuthenticatorCompleted;
        ///            }
        ///        }
        ///    }
        /// --------------------------------------------------------------------------------------------------
        /// iOS AppDelegate:
        ///   namespace InstagramApp.iOS
        ///   {
        ///    [Register("AppDelegate")]
        ///        public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
        ///        {
        ///            public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        ///            {
        ///                global::Xamarin.Forms.Forms.Init();
        ///
        ///                Xamarin.Auth.Presenters.OAuthLoginPresenter.PlatformLogin = (authenticator) =>
        ///                {
        ///                    var oAuthLogin = new OAuthLoginPresenter();
        ///                    oAuthLogin.Login(authenticator);
        ///                 };
        ///                LoadApplication(new App());
        ///
        ///                return base.FinishedLaunching(app, options);
        ///            }
        ///        }
        ///    }
        /// --------------------------------------------------------------------------------------------------
        /// Android OAuthLoginPresenter Class:
        ///   namespace InstagramApp.Droid
        ///   {
        ///    public class OAuthLoginPresenter
        ///        {
        ///            public void Login(Authenticator authenticator)
        ///           {
        ///                Xamarin.Forms.Forms.Context.StartActivity(authenticator.GetUI(Xamarin.Forms.Forms.Context));
        ///            }
        ///        }
        ///    }
        /// --------------------------------------------------------------------------------------------------
        /// Android Manifest:
        ///   namespace InstagramApp.Droid
        ///   {
        ///       [Activity(Label = "InstagramApp", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
        ///       public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        ///       {
        ///           protected override void OnCreate(Bundle bundle)
        ///           {
        ///               TabLayoutResource = Resource.Layout.Tabbar;
        ///               ToolbarResource = Resource.Layout.Toolbar;
        ///
        ///               base.OnCreate(bundle);
        ///
        ///               global::Xamarin.Forms.Forms.Init(this, bundle);
        ///
        ///               Xamarin.Auth.Presenters.OAuthLoginPresenter.PlatformLogin = (authenticator) =>
        ///               {
        ///                   var oAuthLogin = new OAuthLoginPresenter();
        ///                   oAuthLogin.Login(authenticator);
        ///               };
        ///
        ///               LoadApplication(new App());
        ///           }
        ///       }
        ///   }
        /// --------------------------------------------------------------------------------------------------
        /// <param name="navigation"> The standard navigation element of Xamarin. (INavigation VisualElement.Navigation; just type "Navigation" in a ContentPage) </param>
        public static void authenticateInstagram(INavigation navigation)
        {
            var auth = new OAuth2Authenticator(
                Constants.ClientId,
                Constants.Scopes,
                new Uri(Constants.AuthorizationUrl),
                new Uri(Constants.RedirectUri));

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Completed += (sending, eventArgs) =>
            {
                if (eventArgs.IsAuthenticated)
                {
                    Application.Current.Properties["Account"] = eventArgs.Account;
                    navigation.PushAsync(new LoginSuccessPage());
                }
                else
                {
                    // Login canceled
                }
            };
            presenter.Login(auth);
        }
Esempio n. 3
0
        void SignIn_Button(System.Object sender, System.EventArgs e)
        {
            string clientId    = null;
            string redirectUri = null;

            switch (Device.RuntimePlatform)
            {
            case Device.iOS:
                clientId    = AppConstant.Constants.iOSClientId;
                redirectUri = AppConstant.Constants.iOSRedirectUrl;
                break;

            case Device.Android:
                clientId    = AppConstant.Constants.AndroidClientId;
                redirectUri = AppConstant.Constants.AndroidRedirectUrl;
                break;
            }

            account = store.FindAccountsForService(AppConstant.Constants.AppName).FirstOrDefault();

            var authenticator = new OAuth2Authenticator
                                    (clientId, null, AppConstant.Constants.Scope,
                                    new Uri(AppConstant.Constants.AuthorizeUrl),
                                    new Uri(redirectUri),
                                    new Uri(AppConstant.Constants.AccessTokenUrl),
                                    null, true);

            authenticator.Completed += OnAuthCompleted;
            authenticator.Error     += OnAuthError;

            AuthenticationState.Authenticator = authenticator;

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(authenticator);
        }
        // In this case when we have a login URL to display. We'll use Xamarin.Auth display the login URL.
        // and a WebRedirectAuthenticator class to interept redirects.
        public void LoadAuthenticationuri(IBrowserRedirectReceiver redirectReceiver, Uri uri)
        {
            var authenticator = new BrowserWebAuthenticator(uri, Constants.RedirectUri);

            authenticator.Completed += (sender, eventArgs) =>
            {
                redirectReceiver.ProcessUri(authenticator.RedirectUrl);
            };

            authenticator.Error += (object sender, AuthenticatorErrorEventArgs e) =>
            {
                Console.WriteLine($"Error: {e}");
            };

            AuthenticationState.Authenticator = authenticator;

            // With Xamarin.Auth, the native presenters (Login UI) is initialized in
            // the platform specific projects.
            //
            // See below for details on using Xamarin.Auth
            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(authenticator);
        }
Esempio n. 5
0
        void OnFacebookLoginClicked(object sender, EventArgs e)
        {
            string clientId    = null;
            string redirectUri = null;

            switch (Device.RuntimePlatform)
            {
            case Device.iOS:
                clientId    = Constants.FacebookiOSClientId;
                redirectUri = Constants.FacebookiOSRedirectUrl;
                break;

            case Device.Android:
                clientId    = Constants.FacebookAndroidClientId;
                redirectUri = Constants.FacebookAndroidRedirectUrl;
                break;
            }

            account = store.FindAccountsForService(Constants.AppName).FirstOrDefault();

            var authenticator = new OAuth2Authenticator(
                clientId,
                Constants.FacebookScope,
                new Uri(Constants.FacebookAuthorizeUrl),
                new Uri(Constants.FacebookAccessTokenUrl),
                null);

            authenticator.Completed += OnAuthCompleted;
            authenticator.Error     += OnAuthError;

            AuthenticationState.Authenticator = authenticator;

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(authenticator);
        }
Esempio n. 6
0
        public static void CallTodoistAuth()
        {
            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(todoistAuthenticator);
        }
        public IObservable <Dictionary <string, string> > Authenticate(OAuth2 oauth2Info)
        {
            OAuth2Authenticator auth;

            if (oauth2Info.OAuth_UriAccessToken_UriRequestToken != null)
            {
                auth = new OAuth2Authenticator(
                    clientId: oauth2Info.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                    clientSecret: oauth2Info.OAuth_SecretKey_ConsumerSecret_APISecret,
                    scope: oauth2Info.OAuth2_Scope,
                    authorizeUrl: oauth2Info.OAuth_UriAuthorization,
                    redirectUrl: oauth2Info.OAuth_UriCallbackAKARedirect,
                    accessTokenUrl: oauth2Info.OAuth_UriAccessToken_UriRequestToken,
                    isUsingNativeUI: oauth2Info.UsingNativeUI
                    );
            }
            else
            {
                auth = new OAuth2Authenticator(
                    clientId: oauth2Info.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                    scope: oauth2Info.OAuth2_Scope,
                    authorizeUrl: oauth2Info.OAuth_UriAuthorization,
                    redirectUrl: oauth2Info.OAuth_UriCallbackAKARedirect,
                    isUsingNativeUI: oauth2Info.UsingNativeUI
                    );
            }


            auth.AllowCancel             = oauth2Info.AllowCancel;
            auth.ClearCookiesBeforeLogin = oauth2Info.ResetData;
            if (!string.IsNullOrEmpty(oauth2Info.Title))
            {
                auth.Title = oauth2Info.Title;
            }

            AuthenticationState.Authenticator = auth;

            IObservable <Dictionary <string, string> > observable = Observable.Merge(
                Observable.FromEventPattern <EventHandler <AuthenticatorCompletedEventArgs>, AuthenticatorCompletedEventArgs>(
                    h => auth.Completed += h,
                    h => auth.Completed -= h)
                .Select(eventPattern =>
            {
                Dictionary <string, string> authDict = new Dictionary <string, string>();

                if (eventPattern.EventArgs.IsAuthenticated)
                {
                    if (eventPattern?.EventArgs?.Account?.Properties.ContainsKey("access_token") == true)
                    {
                        authDict.Add("access_token", eventPattern.EventArgs.Account.Properties["access_token"]);
                    }


                    if (eventPattern?.EventArgs?.Account?.Properties.ContainsKey("refresh_token") == true)
                    {
                        authDict.Add("refresh_token", eventPattern.EventArgs.Account.Properties["refresh_token"]);
                    }
                }

                return(authDict);
            }),
                Observable.FromEventPattern <EventHandler <AuthenticatorErrorEventArgs>, AuthenticatorErrorEventArgs>(
                    h => auth.Error += h,
                    h => auth.Error -= h).Select(eventPattern => new Dictionary <string, string>())
                ).Select((authDict) => {
                if (!authDict.ContainsKey("access_token") || string.IsNullOrEmpty(authDict["access_token"]))
                {
                    Observable.Throw <OAuthAuthenticationErrorException>(new OAuthAuthenticationErrorException());
                }

                AuthenticationState.Authenticator = null;

                return(authDict);
            });


            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(auth);

            return(observable);
        }
Esempio n. 8
0
        protected void ButtonGoogle_Clicked(object sender, EventArgs e)
        {
            authenticator
                = new Xamarin.Auth.OAuth2Authenticator
                  (
                      clientId:
                      new Func <string>
                      (
                          () =>
            {
                string retval_client_id = "oops something is wrong!";

                // some people are sending the same AppID for google and other providers
                // not sure, but google (and others) might check AppID for Native/Installed apps
                // Android and iOS against UserAgent in request from
                // CustomTabs and SFSafariViewContorller
                // TODO: send deliberately wrong AppID and note behaviour for the future
                // fitbit does not care - server side setup is quite liberal
                switch (Xamarin.Forms.Device.RuntimePlatform)
                {
                case "Android":
                    retval_client_id = "1093596514437-d3rpjj7clslhdg3uv365qpodsl5tq4fn.apps.googleusercontent.com";
                    break;

                case "iOS":
                    retval_client_id = "1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh.apps.googleusercontent.com";
                    break;

                case "Windows":
                    retval_client_id = "1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh.apps.googleusercontent.com";
                    break;
                }
                return(retval_client_id);
            }
                      ).Invoke(),
                      clientSecret: null,  // null or ""
                      authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
                      accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"),
                      redirectUrl:
                      new Func <Uri>
                      (
                          () =>
            {
                string uri = null;

                // some people are sending the same AppID for google and other providers
                // not sure, but google (and others) might check AppID for Native/Installed apps
                // Android and iOS against UserAgent in request from
                // CustomTabs and SFSafariViewContorller
                // TODO: send deliberately wrong AppID and note behaviour for the future
                // fitbit does not care - server side setup is quite liberal
                switch (Xamarin.Forms.Device.RuntimePlatform)
                {
                case "Android":
                    uri =
                        "com.xamarin.traditional.standard.samples.oauth.providers.android:/oauth2redirect"
                        //"com.googleusercontent.apps.1093596514437-d3rpjj7clslhdg3uv365qpodsl5tq4fn:/oauth2redirect"
                    ;
                    break;

                case "iOS":
                    uri =
                        "com.xamarin.traditional.standard.samples.oauth.providers.ios:/oauth2redirect"
                        //"com.googleusercontent.apps.1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh:/oauth2redirect"
                    ;
                    break;

                case "Windows":
                    uri =
                        "com.xamarin.traditional.standard.samples.oauth.providers.ios:/oauth2redirect"
                        //"com.googleusercontent.apps.1093596514437-cajdhnien8cpenof8rrdlphdrboo56jh:/oauth2redirect"
                    ;
                    break;
                }

                return(new Uri(uri));
            }
                      ).Invoke(),
                      scope:
                      //"profile"
                      "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login"
                      ,
                      getUsernameAsync: null,
                      isUsingNativeUI: native_ui
                  )
                {
                AllowCancel = true,
                };

            authenticator.Completed +=
                (s, ea) =>
            {
                StringBuilder sb = new StringBuilder();

                if (ea.Account != null && ea.Account.Properties != null)
                {
                    sb.Append("Token = ").AppendLine($"{ea.Account.Properties["access_token"]}");
                }
                else
                {
                    sb.Append("Not authenticated ").AppendLine($"Account.Properties does not exist");
                }

                DisplayAlert
                (
                    "Authentication Results",
                    sb.ToString(),
                    "OK"
                );

                return;
            };

            authenticator.Error +=
                (s, ea) =>
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Error = ").AppendLine($"{ea.Message}");

                DisplayAlert
                (
                    "Authentication Error",
                    sb.ToString(),
                    "OK"
                );
                return;
            };

            AuthenticationState.Authenticator = authenticator;

            if (forms_implementation_renderers)
            {
                // Renderers Implementaion
                Navigation.PushModalAsync(new Xamarin.Auth.XamarinForms.AuthenticatorPage());
            }
            else
            {
                // Presenters Implementation
                Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
                presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator);
            }

            return;
        }
Esempio n. 9
0
        void FBLogin()
        {
            var authenticator = new Xamarin.Auth.OAuth2Authenticator(
                clientId: OAuthSettingsFacebook.ClientId,
                //clientSecret: OAuthSettingsFacebook.ClientSecret,   // null or ""
                authorizeUrl: new Uri(OAuthSettingsFacebook.AuthorizeUrl),
                //accessTokenUrl: new Uri(OAuthSettingsFacebook.AccessTokenUrl),
                redirectUrl: new Uri($"fb{OAuthSettingsFacebook.ClientId}://authorize"),
                scope: OAuthSettingsFacebook.Scope,
                isUsingNativeUI: true
                )
            {
                AllowCancel = true,
            };

            authenticator.Completed +=
                async(s, ea) =>
            {
                var sb = new StringBuilder();

                if (ea.Account != null && ea.Account.Properties != null)
                {
                    sb.Append("Token = ").AppendLine($"{ea.Account.Properties["access_token"]}");

                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?locale=en_US&fields=id,first_name,last_name,email,picture"), null, ea.Account);
                    var res     = await request.GetResponseAsync();

                    string json = res.GetResponseText();
                    System.Diagnostics.Debug.WriteLine(json);
                    try
                    {
                        var user = Newtonsoft.Json.JsonConvert.DeserializeObject <FacebookUserModel>(json);
                        if (FBLoginResponse != null)
                        {
                            FBLoginResponse(user);
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }
                else
                {
                    sb.Append("Not authenticated ").AppendLine($"Account.Properties does not exist");
                }

                //DisplayAlert
                //		(
                //			"Authentication Results",
                //			sb.ToString(),
                //			"OK"
                //		);

                return;
            };

            authenticator.Error +=
                (s, ea) =>
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Error = ").AppendLine($"{ea.Message}");

                DisplayAlert
                (
                    "Authentication Error",
                    sb.ToString(),
                    "OK"
                );
                return;
            };

            AuthenticationState.Authenticator = authenticator;

            Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
            presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
            presenter.Login(authenticator);

            //Xamarin.Auth.XamarinForms.AuthenticatorPage ap;
            //ap = new Xamarin.Auth.XamarinForms.AuthenticatorPage()
            //{
            //	Authenticator = authenticator,
            //};

            //NavigationPage np = new NavigationPage(ap);
            //await Navigation.PushModalAsync(np);
        }
Esempio n. 10
0
        async void GoogleLogin()
        {
            var authenticator = new Xamarin.Auth.OAuth2Authenticator(
                clientId: OAuthSettingsGoogle.ClientId,
                clientSecret: OAuthSettingsGoogle.ClientSecret,                   // null or ""
                authorizeUrl: new Uri(OAuthSettingsGoogle.AuthorizeUrl),
                accessTokenUrl: new Uri(OAuthSettingsGoogle.AccessTokenUrl),
                redirectUrl: new Uri(OAuthSettingsGoogle.RedirectUrl),
                scope: OAuthSettingsGoogle.Scope,
                getUsernameAsync: null,
                isUsingNativeUI: true
                )
            {
                AllowCancel = true,
            };

            authenticator.Completed +=
                async(s, ea) =>
            {
                var sb = new StringBuilder();

                if (ea.Account != null && ea.Account.Properties != null)
                {
                    sb.Append("Token = ").AppendLine($"{ea.Account.Properties["access_token"]}");

                    var userInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo";
                    var request     = new OAuth2Request("GET", new Uri(userInfoUrl), null, ea.Account);
                    var response    = await request.GetResponseAsync();

                    if (response != null)
                    {
                        string userJson = response.GetResponseText();
                        System.Diagnostics.Debug.WriteLine(userJson);
                        try
                        {
                            var user = Newtonsoft.Json.JsonConvert.DeserializeObject <GoogleUserModel>(userJson);
                            if (GoogleLoginResponse != null)
                            {
                                GoogleLoginResponse(user);
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                }
                else
                {
                    sb.Append("Not authenticated ").AppendLine($"Account.Properties does not exist");
                }

                //DisplayAlert
                //		(
                //			"Authentication Results",
                //			sb.ToString(),
                //			"OK"
                //		);

                return;
            };

            authenticator.Error +=
                (s, ea) =>
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Error = ").AppendLine($"{ea.Message}");

                DisplayAlert
                (
                    "Authentication Error",
                    sb.ToString(),
                    "OK"
                );
                return;
            };

            AuthenticationState.Authenticator = authenticator;

            Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
            presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
            presenter.Login(authenticator);

            //Xamarin.Auth.XamarinForms.AuthenticatorPage ap;
            //ap = new Xamarin.Auth.XamarinForms.AuthenticatorPage()
            //{
            //	Authenticator = authenticator,
            //};

            ////NavigationPage np = new NavigationPage(ap);
            //await Navigation.PushModalAsync(ap);
        }
Esempio n. 11
0
        public static void PresentUILoginScreen
        (
            this Page page,
            Xamarin.Auth.Authenticator authenticator
        )
        {
            if (Settings.IsFormsImplementationRenderers)
            {
                // Renderers Implementaion

                Xamarin.Auth.XamarinForms.AuthenticatorPage ap;
                ap = new Xamarin.Auth.XamarinForms.AuthenticatorPage()
                {
                    Authenticator = authenticator,
                };

                NavigationPage np = new NavigationPage(ap);

                if (Settings.IsFormsNavigationPushModal)
                {
                    System.Diagnostics.Debug.WriteLine("Presenting");
                    System.Diagnostics.Debug.WriteLine("        PushModal");
                    System.Diagnostics.Debug.WriteLine("        Custom Renderers");

                    page.Navigation.PushModalAsync(np);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Presenting");
                    System.Diagnostics.Debug.WriteLine("        Push");
                    System.Diagnostics.Debug.WriteLine("        Custom Renderers");

                    page.Navigation.PushAsync(np);
                }
            }
            else
            {
                // Presenters Implementation

                if (Settings.IsFormsNavigationPushModal)
                {
                    System.Diagnostics.Debug.WriteLine("Presenting");
                    System.Diagnostics.Debug.WriteLine("        PushModal");
                    System.Diagnostics.Debug.WriteLine("        Presenters");

                    Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
                    presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                    presenter.Login(authenticator);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Presenting");
                    System.Diagnostics.Debug.WriteLine("        Push");
                    System.Diagnostics.Debug.WriteLine("        Presenters");

                    Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
                    presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                    presenter.Login(authenticator);
                }
            }

            return;
        }
Esempio n. 12
0
        private void OAuth_Clicked(object sender, EventArgs e)
        {
            try
            {
                var    socialMediaButton           = (Button)sender;
                var    socialMediaName             = socialMediaButton.Text;
                string clientId                    = null;
                string redirectUri                 = null;
                string authorizeURL                = null;
                string accessTokenURL              = null;
                OAuth2Authenticator authenticator_ = null;

                SocialMedia = socialMediaName.ToLower().Contains("google") ? "google" : "facebook";


                switch (SocialMedia)
                {
                case "facebook":
                    authenticator_ = new OAuth2Authenticator

                                     (
                        clientId: Constants.fbClientID,
                        scope: "email",
                        authorizeUrl: new Uri(Constants.FacebookOAuthURL),
                        redirectUrl: new Uri(Constants.redirectURI)

                                     )


                    ;
                    break;

                case "google":

                    switch (Xamarin.Forms.Device.RuntimePlatform)
                    {
                    case Xamarin.Forms.Device.iOS:
                        clientId    = Constants.iOSClientId;
                        redirectUri = Constants.iOSRedirectUrl;
                        break;

                    case Xamarin.Forms.Device.Android:
                        clientId    = Constants.AndroidClientId;
                        redirectUri = Constants.AndroidRedirectUrl;
                        break;
                    }


                    authorizeURL   = Constants.AuthorizeUrl;
                    accessTokenURL = Constants.AccessTokenUrl;

                    authenticator_ = new OAuth2Authenticator(
                        clientId,
                        null,
                        Constants.Scope,
                        new Uri(Constants.AuthorizeUrl),
                        new Uri(redirectUri),
                        new Uri(Constants.AccessTokenUrl),
                        null,
                        true);
                    break;

                default:
                    break;
                }



                authenticator_.Completed += OnAuthCompleted;
                authenticator_.Error     += OnAuthError;

                AuthenticationState.Authenticator = authenticator_;

                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator_);
            }
            catch (Exception ex)
            {
                var log = ex;
                LogService.LogErrors(log.ToString());
            }
        }
        private void BtnLogin_Clicked(object sender, EventArgs e)
        {
            checkConnectivity();

            var authenticator = new OAuth2Authenticator
                                (
                "623999391750-8cep3ajgrnh26gdnmlbjq3376im2gcui.apps.googleusercontent.com",
                "email profile",
                new System.Uri("https://accounts.google.com/o/oauth2/auth"),
                new System.Uri("https://localhost:44312/signin-google")
                                );

            authenticator.AllowCancel = true;

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(authenticator);

            authenticator.Completed += async(senders, obj) =>
            {
                if (obj.IsAuthenticated)
                {
                    Debug.WriteLine("Dit doet iets");
                    var clientData = new HttpClient();

                    //call google api to fetch logged in user profile info
                    token = obj.Account.Properties["access_token"];
                    var resData = await clientData.GetAsync("https://www.googleapis.com/oauth2/v3/userinfo?access_token=" + obj.Account.Properties["access_token"]);

                    var jsonData = await resData.Content.ReadAsStringAsync();

                    //deserlize the jsondata and intilize in GoogleAuthClass
                    GoogleLogin googleObject = JsonConvert.DeserializeObject <GoogleLogin>(jsonData);

                    //you can access following property after login
                    string email = googleObject.email;
                    string name  = googleObject.name;

                    GebruikerV2 gebruikerInfo = await LoginRepository.CheckLogin(googleObject);

                    if (gebruikerInfo != null)
                    {
                        Navigation.PushAsync(new RondeOverzichtPage(gebruikerInfo));
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                        Debug.WriteLine($"Email:{gebruikerInfo.Email}, Gebruikersnaam: {gebruikerInfo.name}, GebruikersId: {gebruikerInfo.GebruikerId}");
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                    }
                    else
                    {
                        Navigation.PopAsync();
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                        Debug.WriteLine("Failed for some reason");
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                    }
                }
                else
                {
                    //Authentication fail
                    //write the code to handle when auth failed
                    //De gebruiker wordt al terug naar de login pagina gestuurd als het inloggen mislukt is
                }
            };
            authenticator.Error += onAuthError;
        }
        /// <summary>
        /// Authentication in this instance refers to the third party authenticator, not our service.
        /// </summary>
        /// <param name="navigation"></param>
        public void startAuthentication(INavigation navigation)
        {
            Debug.WriteLine("DHB:ThirdPartyAuthentiator:startAuthentication start");
            this.navigation = navigation;

            if (authorizeUrl == null)
            {
                // default to facebook as google doesn't work on all platforms.
                configForFacebook();
            }

            /*
             * if (Device.OS == TargetPlatform.iOS) {
             *  // clientId; clientSecret; permissionsRequest; authorizeUrl; redirectUrl; accessTokenUrl; username; isNativeUI
             *  authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
             * } else if (Device.OS == TargetPlatform.Android) {
             *  authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
             * } else {
             *  return;  // no oauth available.
             * }
             */
            if (method == METHOD_FACEBOOK)
            {
                //authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
                //authenticator = new OAuth2Authenticator(clientId, null, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
                //authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, true);
                //authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectYrl, usernameAsync, isUsingNativeUI);
                //authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl, null, false);
                //authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl, null, true);
                authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl);
                //authenticator.Scheme =
            }
            else if (method == METHOD_GOOGLE)
            {
                authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, true);
            }
            else
            {
                return;  // no oauth available.
            }

            // hook up listeners for the auth events.
            authenticator.Completed += OnAuthCompleted;
            authenticator.Error     += OnAuthError;

            Device.OnPlatform(iOS: () =>
            {
                // init the ui
                PlatformSpecificCalls.authInit();
                // and launch...
                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator);
            },
                              Android: () =>
            {
                // why does this work??? there's no tie to the authenticator...
                // Note: According to facebook docs, this only works if fbook installed on the device (have not tested).
                //navigation.PushModalAsync(new OAuthLoginPage());

                //navigation.PushModalAsync(new Xamarin.Auth.XamarinForms.AuthenticatorPage()); fail

                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator);

                //PlatformSpecificCalls.authInit();

                /* This produces a blank page...   */

                /*
                 * Xamarin.Auth.XamarinForms.AuthenticatorPage ap;
                 * ap = new Xamarin.Auth.XamarinForms.AuthenticatorPage() {
                 *  Authenticator = authenticator,
                 * };
                 * NavigationPage np = new NavigationPage(ap);
                 * navigation.PushModalAsync(np);
                 * //navigation.PushAsync(np);
                 * // */
            }
                              );
            Debug.WriteLine("DHB:ThirdPartyAuthentiator:startAuthentication end");
        }
Esempio n. 15
0
        private void OnLoginButtonTapped()
        {
            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(_authenticator);
        }
Esempio n. 16
0
        public LoginView()
        {
            try
            {
                InitializeComponent();

                store   = AccountStore.Create();
                account = store.FindAccountsForService(Constants.AppName).FirstOrDefault();

                this.Title = "Login";

                GoRegister.Clicked += async(sender, args) =>
                {
                    await Navigation.PushModalAsync(new NavigationPage(new RegisterView()));
                };

                DoLogin.Clicked += async(sender, args) =>
                {
                    try
                    {
                        bool comprobarPermisos = await ComprobarPermisos();

                        if (comprobarPermisos)
                        {
                            //Loadding.IsRunning = true;
                            bool resgisted = await new UserViewModel().LoginUser(email.Text, password.Text);
                            if (resgisted)
                            {
                                //Loadding.IsRunning = false;
                                await Navigation.PushModalAsync(new NavigationPage(new FastVehicleView()));
                            }
                            else
                            {
                                //Loadding.IsRunning = false;
                                await DisplayAlert("Advertencia", "Tus datos no son correctos", "OK");

                                password.Text = "";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                };

                RecoverPassword.Clicked += async(sender, args) =>
                {
                    if (!string.IsNullOrWhiteSpace(email.Text))
                    {
                        await new UserViewModel().RecoverPassword(email.Text);
                        await DisplayAlert("Advertencia", "Email de recuperación enviado", "OK");
                    }
                    else
                    {
                        await DisplayAlert("Advertencia", "Introduce un email", "OK");
                    }
                };

                DoLoginGoogle.Clicked += async(sender, args) =>
                {
                    bool comprobarPermisos = await ComprobarPermisos();

                    if (comprobarPermisos)
                    {
                        string clientId    = null;
                        string redirectUri = null;

                        switch (Device.RuntimePlatform)
                        {
                        case Device.iOS:
                            clientId    = Constants.iOSClientId;
                            redirectUri = Constants.iOSRedirectUrl;
                            break;

                        case Device.Android:
                            clientId    = Constants.AndroidClientId;
                            redirectUri = Constants.AndroidRedirectUrl;
                            break;
                        }

                        try
                        {
                            var authenticator = new OAuth2Authenticator(
                                clientId,
                                null,
                                Constants.Scope,
                                new Uri(Constants.AuthorizeUrl),
                                new Uri(redirectUri),
                                new Uri(Constants.AccessTokenUrl),
                                null,
                                true);

                            authenticator.Completed += OnAuthCompleted;
                            authenticator.Error     += OnAuthError;

                            AuthenticationState.Authenticator = authenticator;

                            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                            presenter.Login(authenticator);
                        }
                        catch (Exception ex)
                        {
                            await DisplayAlert("Error", "No se ha podido hacer login con GOOGLE", "OK");
                        }
                    }
                };

                DoLoginFacebook.Clicked += async(sender, args) =>
                {
                    bool comprobarPermisos = await ComprobarPermisos();

                    if (comprobarPermisos)
                    {
                        var apiRequest =
                            "https://www.facebook.com/dialog/oauth?client_id=" +
                            "1949845268596950"
                            + "&display=popup&response_type=token&redirect_uri=https://securtraffic-49c23.firebaseapp.com/__/auth/handler";

                        var webView = new WebView
                        {
                            Source        = apiRequest,
                            HeightRequest = 1
                        };

                        webView.Navigated += WebViewOnNavigated;

                        Content = webView;
                    }
                };
            }
            catch (Exception ex)
            {
                Debug.WriteLine("LoginView: " + ex.Message);
            }
        }
Esempio n. 17
0
        async void authButton_Clicked(object sender, EventArgs e)
        {
            if (!Settings.IsLoggedIn)
            {
                //await azureService.Initialize();
                //var authenticator = await DependencyService.Get<IAuthentication>();
                //var user = authenticator.LoginAsync(azureService.MobileService, MobileServiceAuthenticationProvider.Facebook);
                //if (user == null)
                //    return;

                //pull latest data from server:
                //var coffees = await azureService.GetCoffees();
                //Coffees.ReplaceRange(coffees);
                //SortCoffees();
            }

            //OAuth2Authenticator auth = new OAuth2Authenticator
            authenticator = new OAuth2Authenticator
                            (
                clientId: "424301387946620",
                scope: "",
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"),
                // switch for new Native UI API
                //      true = Android Custom Tabs and/or iOS Safari View Controller
                //      false = Embedded Browsers used (Android WebView, iOS UIWebView)
                //  default = false  (not using NEW native UI)
                isUsingNativeUI: true
                            );

            authenticator.Completed += OnAuthCompleted;
            authenticator.Error     += OnAuthError;

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(authenticator);

            //authenticator
            //    = new Xamarin.Auth.OAuth2Authenticator
            //    (
            //        /*
            //        clientId: "185391188679-9pa23l08ein4m4nmqccr9jm01udf3oup.apps.googleusercontent.com",
            //        scope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login",
            //        authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
            //        redirectUrl: new Uri
            //                        (
            //                            "comauthenticationapp://localhost"
            //                        //"com.authentication.app://localhost"
            //                        //"com-authentication-app://localhost"
            //                        ),
            //        */
            //        clientId:
            //            new Func<string>
            //               (
            //                    () =>
            //                    {
            //                        string retval_client_id = "oops something is wrong!";

            //                        // some people are sending the same AppID for google and other providers
            //                        // not sure, but google (and others) might check AppID for Native/Installed apps
            //                        // Android and iOS against UserAgent in request from
            //                        // CustomTabs and SFSafariViewContorller
            //                        // TODO: send deliberately wrong AppID and note behaviour for the future
            //                        // fitbit does not care - server side setup is quite liberal
            //                        switch (Xamarin.Forms.Device.RuntimePlatform)
            //                        {
            //                            case "iOS":
            //                                retval_client_id = "228CVW";
            //                                break;
            //                            case "Android":
            //                                retval_client_id = "228CVW";
            //                                break;
            //                        }
            //                        return retval_client_id;
            //                    }
            //              ).Invoke(),
            //        authorizeUrl: new Uri("https://www.fitbit.com/oauth2/authorize"),
            //        redirectUrl: new Uri("xamarin-auth://localhost"),
            //        scope: "profile",
            //        getUsernameAsync: null,
            //        isUsingNativeUI: false
            //    )
            //    {
            //        AllowCancel = true,
            //    };

            //NavigateLoginPage();

            return;
        }
        public override void Login(Action <string, string> success, Action <Exception> error)
        {
            _successCallback = success;
            _errorCallback   = error;

            _authenticator = null;
            _authenticator = new OAuth2Authenticator(
                ClientId,
                ApiSecret,
                "",
                new Uri("https://www.yammer.com/oauth2/authorize"),
                new Uri(RedirectUrl),
                new Uri("https://www.yammer.com/oauth2/access_token.json"),
                isUsingNativeUI: true)
            {
                ShowErrors = true,
            };

            _authenticator.Completed += async(sender, e) =>
            {
                if (e.Account != null && e.Account.Properties.ContainsKey("access_token"))
                {
                    _token = e.Account.Properties["access_token"];
                    dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(_token);
                    await AppProperties.AddOrUpdate("access_token", _token);

                    await AppProperties.AddOrUpdate("token", data["token"].ToString());

                    AppSettings.Token = data["token"].ToString();
                    //await AppProperties.AddOrUpdate("username", data["user_id"]);
                    //await AppProperties.AddOrUpdate("network_permalink", data["network_permalink"]);
                    //await AppProperties.AddOrUpdate("network_id", data["network_id"]);
                    await AppProperties.AddOrUpdate("user_id", data["user_id"].ToString());

                    AppSettings.UserId = data["user_id"].ToString();
                }
                if (e.Account != null && e.Account.Properties.ContainsKey("network"))
                {
                    var network = e.Account.Properties["network"];
                    //await AppProperties.AddOrUpdate("network", network);
                }
                if (e.Account != null && e.Account.Properties.ContainsKey("user"))
                {
                    var user = e.Account.Properties["user"];
                    //await AppProperties.AddOrUpdate("user", user);
                    //dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(user);
                    //await AppProperties.AddOrUpdate("full_name", data["full_name"]);
                    //await AppProperties.AddOrUpdate("network_domains", data["network_domains"]);
                }

                _successCallback?.Invoke(_token, null);
            };

            _authenticator.Error += (sender, e) =>
            {
                //There might be a better way in the future other than ignoring invalid_request error
                if (string.IsNullOrEmpty(_token) || !e.Message.Contains("invalid_request"))
                {
                    _errorCallback?.Invoke(e.Exception);
                }
            };

            Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
            presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
            presenter.Login(_authenticator);
        }
Esempio n. 19
0
 void PresentLoginView()
 {
     _authPresenter.Login(_authenticator);
 }