コード例 #1
0
 private async Task UpdateExternalAuthLink(ExternalAuthenticationLink externalAuthenticationLink,
                                           string accessToken, DateTime expiresDate, string scopesToAdd = null, string refreshToken = null)
 {
     if (externalAuthenticationLink == null || string.IsNullOrEmpty(accessToken))
     {
         return;
     }
     externalAuthenticationLink.AccessToken            = accessToken;
     externalAuthenticationLink.AccessTokenExpiresDate = expiresDate;
     if (!string.IsNullOrEmpty(refreshToken))
     {
         externalAuthenticationLink.RefreshToken = refreshToken;
     }
     _externalAuthLinkRepository.Update(externalAuthenticationLink);
     await _context.SaveChangesAsync();
 }
コード例 #2
0
        private async Task <ExternalAuthenticationAccessTokenUpdateResponse> UpdateExternalAccessToken(string refreshToken, ExternalAuthenticationLink externalAuthenticationLink)
        {
            if (string.IsNullOrEmpty(refreshToken))
            {
                throw new ArgumentException(nameof(refreshToken));
            }

            var httpContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("client_id", _googleExternalAuthenticationConfiguration.ClientId),
                new KeyValuePair <string, string>("client_secret", _googleExternalAuthenticationConfiguration.ClientSecret),
                new KeyValuePair <string, string>("grant_type", IdentityServerConstants.PersistedGrantTypes.RefreshToken),
                new KeyValuePair <string, string>("refresh_token", refreshToken)
            });

            ExternalAuthenticationAccessTokenUpdateResponse refreshResponse = null;

            using (var client = new HttpClient())
                using (var response = await client.PostAsync(GoogleDefaults.TokenEndpoint, httpContent))
                {
                    if (response?.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception("Refresh Access Token request failed. User token might be invalid");
                    }
                    var responseAsString = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(responseAsString))
                    {
                        refreshResponse = JsonConvert.DeserializeObject <ExternalAuthenticationAccessTokenUpdateResponse>(responseAsString);
                    }
                }

            if (refreshResponse?.AccessToken == null)
            {
                throw new Exception("Refresh Access Token request failed. User token might be invalid");
            }

            var expires = DateTime.UtcNow.AddSeconds(refreshResponse.ExpiresIn);

            await UpdateExternalAuthLink(externalAuthenticationLink, refreshResponse.AccessToken, expires);

            return(refreshResponse);
        }