Ejemplo n.º 1
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,
            });
        }
        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);
            }
        }