Ejemplo n.º 1
0
        protected override void Authorize()
        {
            WindowThreadOptions <WebView> windowThreadOptions = new WindowThreadOptions <WebView>
            {
                WindowInitialization = window =>
                {
                    window.Title        = "Spotify Authorization";
                    window.AllowedHosts = new List <string> {
                        "accounts.spotify.com", "localhost", string.Empty
                    };
                    window.SetSize(new Size(475, 512));
                },
                BeforeWindowShownAction = window =>
                {
                    window.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                    {
                        AuthorizationCodeFlow.Authorize(url => window.NavigateTo(url), this.Scopes, this.State, this.ShowDialog, "en");
                    }));
                },
                OnWindowClosingAction = window => this.abortAuthEvent.Set()
            };

            this.webViewWindowThread = ThreadManager.Instance.CreateWindowThread(ApartmentState.STA, windowThreadOptions);
            this.webViewWindowThread.IsBackground = true;
            this.webViewWindowThread.ThreadName   = $"{nameof(ToastifyWebAuth)}_{nameof(WebView)}_Thread";
            this.webViewWindowThread.Start();
        }
Ejemplo n.º 2
0
        protected override void Authorize()
        {
            //WindowThreadOptions<WebView> windowThreadOptions = new WindowThreadOptions<WebView>
            //{
            //    WindowInitialization = window =>
            //    {
            //        window.Title = "Spotify Authorization";
            //        // TODO: AllowedHosts
            //        //window.AllowedHosts = new List<string> { "accounts.spotify.com", "localhost", string.Empty };
            //        window.SetSize(new Size(475, 512));
            //    },
            //    BeforeWindowShownAction = window =>
            //    {
            //        window.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            //        {
            //            AuthorizationCodeFlow.Authorize(url => window.NavigateTo(url), this.Scopes, this.State, this.ShowDialog, "en");
            //        }));
            //    },
            //    OnWindowClosingAction = window => this.abortAuthEvent.Set()
            //};

            //this.webViewWindowThread = ThreadManager.Instance.CreateWindowThread(ApartmentState.STA, windowThreadOptions);
            //this.webViewWindowThread.IsBackground = true;
            //this.webViewWindowThread.ThreadName = $"{nameof(ToastifyWebAuth)}_{nameof(WebView)}_Thread";
            //this.webViewWindowThread.Start();

            AuthorizationCodeFlow.Authorize(url =>
            {
                string spotifyLoginUrl = Convert.ToBase64String(Encoding.UTF8.GetBytes(url));
                string toastifyAuthUrl = "https://aleab.github.io/toastify/spotify/authorize";
                toastifyAuthUrl        = $"{toastifyAuthUrl}?toastifyPort={this.authHttpServer.Port}&redirectUrl={Uri.EscapeDataString(spotifyLoginUrl)}";
                Process.Start(toastifyAuthUrl);
            }, this.Scopes, this.State, this.ShowDialog, "en");
        }
 //Private setup function called by each test to ensure that the spotify api can be successfully called
 private async Task SetupCredentials()
 {
     if (Creds == null)
     {
         SecretManager.InitializeAppAPIKeys();
         Creds = await AuthorizationCodeFlow.RefreshAccessToken(SecretManager.RefreshToken, SecretManager.client_id, SecretManager.client_secret);
     }
 }
        public void CreateAuthorizationUrl_NoScopes()
        {
            const string AuthorizationUrl = "https://accounts.spotify.com/authorize" +
                                            "?response_type=code" +
                                            "&client_id=CLIENT_ID" +
                                            "&redirect_uri=REDIRECT_URI";

            Assert.AreEqual(
                expected: new(AuthorizationUrl),
                actual: AuthorizationCodeFlow.CreateAuthorizationUri("CLIENT_ID", "REDIRECT_URI"));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates Google Drive service object with correct credentials.
        /// </summary>
        /// <param name="refreshToken">Refresh Token to use.</param>
        /// <returns>Google Drive service object.</returns>
        private async Task <DriveService> CreateService(string refreshToken)
        {
            var initializer =
                new AuthorizationCodeFlow.Initializer(
                    "https://accounts.google.com/o/oauth2/auth",
                    "https://accounts.google.com/o/oauth2/token")
            {
                ClientSecrets =
                    new ClientSecrets
                {
                    ClientId     = Constants.GoogleDriveSyncClientId,
                    ClientSecret = Constants.GoogleDriveSyncClientSecret
                }
            };

            // Hardcoded Google Drive Sync secret.
            string[] scopes = { DriveService.Scope.DriveReadonly };
            initializer.Scopes = scopes;

            using (var codeFlow = new AuthorizationCodeFlow(initializer))
            {
                try
                {
                    var token = await GoogleRequestHelper.Execute(
                        ct => codeFlow.RefreshTokenAsync("user", refreshToken, ct),
                        this.CancellationToken);

                    var credential = new UserCredential(codeFlow, "user", token);

                    var service =
                        new DriveService(
                            new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = Utils.Constants.ApplicationName
                    });

                    return(service);
                }
                catch (Exception e)
                {
                    if (this.CancellationToken.IsCancellationRequested)
                    {
                        this.Log.LogMessage("Operation was cancelled.");
                        throw;
                    }

                    this.StatusAccumulator.FailureOccurred();
                    this.Log.LogError("Authorization error.", e);
                    throw;
                }
            }
        }
Ejemplo n.º 6
0
        private async Task Run()
        {
            //           var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            //   new ClientSecrets
            //   {
            //       ClientId = "300353354116-bigm93gijg4013dro7qnkg4je67curtg.apps.googleusercontent.com",
            //       ClientSecret = "WcoDYC0_qDxaxYRd4mcWxKHk"
            //   },
            //   new[] { Google.Apis.Games.v1.GamesService.Scope.Games },
            //   "user"   ,
            //   new System.Threading.CancellationToken()
            //);

            var ctoken = new System.Threading.CancellationToken();

            var clientSecrets = new ClientSecrets
            {
                ClientId     = "300353354116-bigm93gijg4013dro7qnkg4je67curtg.apps.googleusercontent.com",
                ClientSecret = "WcoDYC0_qDxaxYRd4mcWxKHk"
            };

            var flow = new AuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes        = new string[] { "https://www.googleapis.com/auth/games" }
            });

            var token = await flow.ExchangeCodeForTokenAsync("112828434304919930917", "4/AAA32YZmmJhZPLS4A07_EMyARC23WQO5SeIduqgJx52C3CEYK6Cp9ePpO_qHeH4Rx0saT4EWL-vbV5Ei5l0ajy4", "https://localhost:44301", ctoken);

            // Create the service.

            var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer    {
                ClientSecrets = clientSecrets
            }), "user", token);


            var service = new Google.Apis.Games.v1.GamesService(new Google.Apis.Services.BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                ApplicationName       = "PaintTheTown",
                ApiKey = "AIzaSyCeCYL0Z6mw-PcUA1dzd4H7HxcFFN-vuZ4",
            });

            var result = service.Achievements.Increment("CgkIhPPR894IEAIQAA", 1);

            // GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync("eyJhbGciOiJSUzI1NiIsImtpZCI6ImMwNmEyMTQ5YjdmOTU3MjgwNTJhOTg1YWRlY2JmNWRlMDQ3Y2RhNmYifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vcGFpbnR0aGV0b3duLWViODI3IiwibmFtZSI6IkrDvHJnZW4gU2Now7ZuZXIiLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDMuZ29vZ2xldXNlcmNvbnRlbnQuY29tLy1idUFiRGluaWotMC9BQUFBQUFBQUFBSS9BQUFBQUFBQUFBQS9BRmlZb2YzaW5PRmR3WXpoQlFfeThEU2dTTnVuNDBPRW53L3M5Ni1jL3Bob3RvLmpwZyIsImF1ZCI6InBhaW50dGhldG93bi1lYjgyNyIsImF1dGhfdGltZSI6MTUyMTA1NzM3MiwidXNlcl9pZCI6IjRBS0g4V2pxMUxVNWRxV2ZZR2h4Z01uY3U2UjIiLCJzdWIiOiI0QUtIOFdqcTFMVTVkcVdmWUdoeGdNbmN1NlIyIiwiaWF0IjoxNTIzMjk2NjUwLCJleHAiOjE1MjMzMDAyNTAsImVtYWlsIjoidGhlam9laWF1dEBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJnb29nbGUuY29tIjpbIjExMjgyODQzNDMwNDkxOTkzMDkxNyJdLCJlbWFpbCI6WyJ0aGVqb2VpYXV0QGdtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6Imdvb2dsZS5jb20ifX0.NvUN24H6jdO31lv1DLx8l-APoHSD6rq7gwCVIKoaQIgxi1FZur3XvJDAG2gELZCF_wrV4SiA2zpX-raKtmVjXb-JR7CecZIBQ4Ryi7zYW3h7jiTOKn75_Nn4ZqxOaz5xHSTKXwYwP21TeZB5NYcU1Bu5x4GAL2AN7XIV8Iby21t3Qx9Y7lc9cMdtXlRYs1oJ9Q8vbRPQ6La-W0lJYbPZtj8RYC60Nvaz43ckrJ3Vo1z4gNfVhNb_9Uz9aSfPPAFIelyP0ZJ4ucxH75PsfmC64zNPgOSbhN_P8z34NHSd7MMKkFAkYb4dbqYsQV4NxOSA2SCwqQvvWWW88mnBqLHaIA",null,false);

            // Run the request.
            Console.WriteLine("Executing a list request...");
            result.Execute();
            var asfsa = service.Achievements.List("112828434304919930917");
        }
        public void CreateAuthorizationUrl_MultipleScopes()
        {
            const string AuthorizationUrl = "https://accounts.spotify.com/authorize" +
                                            "?response_type=code" +
                                            "&client_id=CLIENT_ID" +
                                            "&redirect_uri=REDIRECT_URI" +
                                            "&scope=ugc-image-upload%20streaming%20playlist-read-collaborative";

            Assert.AreEqual(
                expected: new(AuthorizationUrl),
                actual: AuthorizationCodeFlow.CreateAuthorizationUri(
                    "CLIENT_ID",
                    "REDIRECT_URI",
                    scopes: AuthorizationScopes.UgcImageUpload | AuthorizationScopes.Streaming | AuthorizationScopes.PlaylistReadCollaborative));
        }
        public void CreateAuthorizationUrl_SingleScope()
        {
            const string AuthorizationUrl = "https://accounts.spotify.com/authorize" +
                                            "?response_type=code" +
                                            "&client_id=CLIENT_ID" +
                                            "&redirect_uri=REDIRECT_URI" +
                                            "&scope=ugc-image-upload";

            Assert.AreEqual(
                expected: new(AuthorizationUrl),
                actual: AuthorizationCodeFlow.CreateAuthorizationUri(
                    "CLIENT_ID",
                    "REDIRECT_URI",
                    scopes: AuthorizationScopes.UgcImageUpload));
        }
Ejemplo n.º 9
0
        public async Task InitializeAsync()
        {
            var initializer = new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.Initializer(_authServerUrl, _tokenServerUrl);

            initializer.ClientSecrets = new ClientSecrets()
            {
                ClientId     = "<CLIENTID>",
                ClientSecret = "<CLIENTSECRET>"
            };
            initializer.Scopes    = Scopes;
            initializer.DataStore = new StorageDataStore();
            var flow = new AuthorizationCodeFlow(initializer);
            // try to load access token response from storage
            TokenResponse tokenResponse = null;

            try
            {
                tokenResponse = await flow.LoadTokenAsync(_userId, CancellationToken.None);
            }
            catch (Exception)
            {
            }
            // if access token response is not found, exchange device code for access token
            if (tokenResponse == null)
            {
                TokenRequest tokenRequest = new DeviceCodeTokenRequest()
                {
                    ClientId     = initializer.ClientSecrets.ClientId,
                    ClientSecret = initializer.ClientSecrets.ClientSecret,
                    Code         = _deviceCode,
                    Scope        = Scopes[0]
                };
                tokenResponse = await flow.FetchTokenAsync(_userId, tokenRequest, CancellationToken.None);

                await flow.DataStore.StoreAsync(_userId, tokenResponse);
            }
            UserCredential credential = new UserCredential(flow, _userId, tokenResponse);

            service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = AppName,
            });
        }
Ejemplo n.º 10
0
        public DriveService GetDriveService(string accessToken, string refreshToken, DateTime issueUtc, long expiresInSeconds, string userId)
        {
            var tokenResponce = new TokenResponse
            {
                AccessToken      = accessToken,
                RefreshToken     = refreshToken,
                IssuedUtc        = issueUtc,
                ExpiresInSeconds = expiresInSeconds
            };

            var authorizationCodeFlow = new AuthorizationCodeFlow(new AuthorizationCodeFlow.Initializer(GoogleAuthConsts.OidcAuthorizationUrl, GoogleAuthConsts.OidcTokenUrl));

            var userCredential = new UserCredential(authorizationCodeFlow, userId, tokenResponce);

            return(new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = userCredential,
                ApplicationName = "",
            }));
        }
Ejemplo n.º 11
0
        public bool Refresh()
        {
            TokenResponse token = new TokenResponse {
                AccessToken  = AccessToken,
                RefreshToken = RefreshToken
            };

            IAuthorizationCodeFlow flow =
                new AuthorizationCodeFlow(new AuthorizationCodeFlow.Initializer(GoogleAuthConsts.AuthorizationUrl, GoogleAuthConsts.TokenUrl)
            {
                ClientSecrets = GoogleSecrets.ToClientSecrets(Broker.Secrets),
                Scopes        = new [] { PlusService.Scope.PlusLogin }
            });

            UserCredential credential = new UserCredential(flow, "me", token);
            bool           success;

            try {
                success = credential.RefreshTokenAsync(CancellationToken.None).Result;
            } catch (AggregateException ex) {
                Log.Error("RefreshTokenAsync failed: ");
                Log.Indent++;
                Log.Error(ex);
                Log.Indent--;
                success = false;
            }

            if (success)
            {
                token       = credential.Token;
                AccessToken = token.AccessToken;
                Log.Debug("Refresh successful: ", AccessToken);
                return(true);
            }
            else
            {
                Log.Error("Refresh failed: ", this);
                return(false);
            }
        }
Ejemplo n.º 12
0
        public async Task connectionmaker()
        {
            var init = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = this.dbconf.ClientID,
                    ClientSecret = this.dbconf.Clientsecret
                },
                Scopes = new string[] { "https://www.googleapis.com/auth/drive" }
            };
            var flow = new AuthorizationCodeFlow(init);

            Token = await flow.RefreshTokenAsync("user", dbconf.RefreshToken, CancellationToken.None);

            credential = GoogleCredential.FromAccessToken(Token.AccessToken);
            service    = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = this.dbconf.ApplicationName,
            });
        }
        static public async Task <bool> IsUserAuthenticated()
        {
            GoogleAuthorizationCodeFlow.Initializer initializer = new GoogleAuthorizationCodeFlow.Initializer();
            var secrets = new ClientSecrets
            {
                ClientSecret = Constants.ClientSecret,
                ClientId     = Constants.ClientID
            };

            initializer.ClientSecrets = secrets;
            initializer.DataStore     = new PasswordVaultDataStore();
            var test  = new AuthorizationCodeFlow(initializer);
            var token = await test.LoadTokenAsync("user", CancellationToken.None);

            if (token == null)
            {
                return(false);
            }
            else
            {
                Constants.Token = token;
                return(true);
            }
        }
Ejemplo n.º 14
0
        /// Request Oauth2 credentials through a third party by providing authorization and token server
        /// URLs.
        public OAuth2CredentialRequest(ClientSecrets secrets, IEnumerable <string> scopes,
                                       string callbackPath, IDataStore dataStore,
                                       string authorizationServerUrl, string tokenServerUrl)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(authorizationServerUrl),
                         "Missing authorization server url");
            Debug.Assert(!string.IsNullOrWhiteSpace(tokenServerUrl),
                         "Missing token server url");

            // Use the generic authorization code flow with the provided authorization and token
            // server urls.
            IsGoogle = false;
            var initializer = new AuthorizationCodeFlow.Initializer(authorizationServerUrl,
                                                                    tokenServerUrl)
            {
                ClientSecrets = secrets,
                Scopes        = scopes,
                DataStore     = dataStore,
            };
            var authFlow     = new AuthorizationCodeFlow(initializer);
            var codeReceiver = new LocalHttpCodeReceiver(callbackPath);

            m_AppFlow = new AuthorizationCodeInstalledApp(authFlow, codeReceiver);
        }
        /// <summary>
        /// Constructs a new authorization code for Windows Phone targeting an installed application flow.
        /// </summary>
        /// <param name="authorizationCodeFlowInitializer">An authorization code flow initializer.</param>
        public AuthorizationCodeWPInstalledApp(AuthorizationCodeFlow.Initializer authorizationCodeFlowInitializer)
        {
            var flow = new AuthorizationCodeFlow(authorizationCodeFlowInitializer);

            innerInstallApp = new AuthorizationCodeInstalledApp(flow, new AuthorizationCodeBroker());
        }
        public async void ShouldFailToAuthorize()
        {
            OAuthCredentials token = await AuthorizationCodeFlow.GetSpotifyTokenCredentials(FakeOAuthCode, FakeClientId, fakeClientSecret, fakeRedirectUrl);

            Assert.True(token.WasError, "Given false authorization codes, auth should fail");
        }