public async Task RefreshTokensAsync_ShouldReturnExpectedResult(InstalledAppInstance installedApp)
        {
            var at        = Guid.NewGuid().ToString();
            var rt        = Guid.NewGuid().ToString();
            var atExpires = TimeSpan.FromMinutes(5).ToString("c");
            var expiresDt = DateTime.Now.Add(TimeSpan.FromMinutes(5));

            var responseBody = $@"{{
                ""access_token"": ""{at}"",
                ""refresh_token"": ""{rt}"",
                ""expires_in"": ""{atExpires}""
            }}";

            _mockHttpMessageHandler.SetupRequest(HttpMethod.Post,
                                                 "https://auth-global.api.smartthings.com/oauth/token")
            .ReturnsResponse(responseBody);
            var result = await _smartThingsAPIHelper.RefreshTokensAsync(installedApp);

            Assert.NotNull(result);

            var expiresDiff = result.AccessToken.ExpiresDT.Subtract(expiresDt).Duration();

            Assert.Equal(installedApp.AccessToken.TokenValue,
                         result.AccessToken.TokenValue);
            Assert.True((expiresDiff <= TimeSpan.FromSeconds(45))); // Due to buffer and proc time
            Assert.False(result.AccessToken.IsExpired);
            Assert.Equal(installedApp.RefreshToken.TokenValue,
                         result.RefreshToken.TokenValue);
        }
コード例 #2
0
        public virtual async Task <InstalledAppInstance> RefreshTokensAsync(InstalledAppInstance installedApp)
        {
            _ = installedApp ??
                throw new ArgumentNullException(nameof(installedApp));
            _ = installedApp.InstalledAppId ??
                throw new ArgumentException("installedApp.InstalledAppId is null",
                                            nameof(installedApp));
            _ = installedApp.AccessToken ??
                throw new ArgumentException("installedApp.AccessToken is null",
                                            nameof(installedApp));
            _ = installedApp.RefreshToken ??
                throw new ArgumentException("installedApp.RefreshToken is null",
                                            nameof(installedApp));

            if (installedApp.RefreshToken.IsExpired)
            {
                throw new ArgumentException("installedApp.RefreshToken is expired!",
                                            nameof(installedApp));
            }

            _logger.LogDebug($"Refreshing tokens for installedApp: {installedApp.InstalledAppId}...");

            if (installedApp.AccessToken.IsExpired)
            {
                _logger.LogDebug($"installedApp: {installedApp.InstalledAppId} has an expired token, attempting to refresh...");
                installedApp = await _smartThingsAPIHelper.RefreshTokensAsync(installedApp).ConfigureAwait(false);
                await StoreInstalledAppAsync(installedApp).ConfigureAwait(false);
            }

            return(installedApp);
        }