Exemplo n.º 1
0
        public async Task AuthorizationPollingAsync(string user)
        {
            GoogleCodeResponse googleCodeResponse = GetGoogleCodeResponse(user);
            GoogleAuthResponse googleAuthResponse = await _googleFitService.AuthorizationPolling(user, googleCodeResponse);

            string token = googleAuthResponse?.access_token;

            SetUserState <GoogleAccessToken>(user, new GoogleAccessToken(token));
            RaiseOnChangeEvent();
        }
Exemplo n.º 2
0
        public async Task <GoogleAuthResponse> AuthorizationPolling(string user, GoogleCodeResponse googleCodeResponse)
        {
            DateTime expiresDateTime = DateTime.UtcNow.AddSeconds(googleCodeResponse.expires_in);
            List <KeyValuePair <string, string> > content = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("client_id", _configuration.ClientId),
                new KeyValuePair <string, string>("client_secret", _configuration.ClientSecret),
                new KeyValuePair <string, string>("device_code", googleCodeResponse.device_code),
                new KeyValuePair <string, string>("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
            };

            while (DateTime.UtcNow < expiresDateTime && string.IsNullOrEmpty(await GetAccessTokenAsync(user)))
            {
                HttpResponseMessage response = await _httpClient.PostAsync("https://oauth2.googleapis.com/token", new FormUrlEncodedContent(content));

                string responseContent = await response.Content.ReadAsStringAsync();

                GoogleAuthResponse googleAuthResponse = JsonConvert.DeserializeObject <GoogleAuthResponse>(responseContent);

                if (response.IsSuccessStatusCode)
                {
                    _cache.SetString(GetCacheKey(CacheKeyRefreshToken, user), googleAuthResponse.refresh_token);
                    _cache.SetString(GetCacheKey(CacheKeyAccessToken, user), googleAuthResponse.access_token, new DistributedCacheEntryOptions
                    {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(googleAuthResponse.expires_in - 30)
                    });

                    return(googleAuthResponse);
                }

                _logger.LogWarning("Error polling google auth endpoint: {statusCode}, {error}", response.StatusCode, googleAuthResponse.error);
                await Task.Delay(googleCodeResponse.interval * 1000);
            }

            return(new GoogleAuthResponse
            {
                access_token = await GetAccessTokenAsync(user)
            });
        }