public async Task <Result> SendUserNotification(string userId, string message)
        {
            var messaging = new AccessTokenClient(AccessTokenClient.ApiDomainBaseAddress);
            var token     = (await messaging.Send(configuration.AldoClientId, configuration.AldoClientSecret)).Token;

            var deployEvent = new MessageReminder(
                new MessageReminderState(MessageReminderStatus.Unread, MessageReminderFreshness.New),
                new MessageReminderGroup(message, 1, MessageReminderUrgency.Urgent));

            var userReq = new UserEventRequest(userId, deployEvent)
            {
                ReferenceId = Guid.NewGuid().ToString(),
                ExpiryTime  = DateTimeExtensions.ItaNow().AddMinutes(6),
                TimeStamp   = DateTimeExtensions.ItaNow()
            };

            var client = new ProactiveEventsClient(ProactiveEventsClient.EuropeEndpoint, token, true);

            var result = await client.Send(userReq);

            if (result.IsSuccessStatusCode)
            {
                return(Result.Ok());
            }

            var errorContent = await result.Content.ReadAsStringAsync();

            var error = $"{result.ReasonPhrase}\n\r{errorContent}";

            return(Result.Fail(error));
        }
示例#2
0
        private void LogOutUserByUserId(string userId)
        {
            if (!string.IsNullOrWhiteSpace(userId))
            {
                Guid uId = new Guid(userId);
                try
                {
                    using (var client = new AccessTokenClient())
                    {
                        var result = client.RemoveAll(uId, "Setting站点工具登出");
                        result.ThrowIfException(true);
                    }

                    using (var useraccoutClient = new UserAccountClient())
                    {
                        var insertLog = useraccoutClient.LogUserAction(new UserLog
                        {
                            Action      = UserActionEnum.LogOut,
                            CreatedTime = DateTime.Now,
                            UserId      = uId,
                            ChannelIn   = nameof(ChannelIn.H5),
                            Content     = "Setting站点内手动登出该用户"
                        });
                        insertLog.ThrowIfException(true);
                    }
                }
                catch (Exception ex)
                {
                    WebLog.LogException(ex);
                }
            }
        }
        public void ConstructorCreatesRestClient()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act

            // Assert
            Assert.NotNull(accessTokenClient.RestClient);
        }
        public void ConstructorCreatesRestClientWithCorrectBaseUrl()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act

            // Assert
            Assert.Equal(ServerConfiguration.BaseUrl.OriginalString, accessTokenClient.RestClient.BaseUrl);
        }
示例#5
0
        public void ConstructorCreatesRestClientWithCorrectBaseUrl()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act

            // Assert
            Assert.Equal(ServerConfiguration.BaseUrl.OriginalString, accessTokenClient.RestClient.BaseUrl);
        }
示例#6
0
        public void ConstructorCreatesRestClient()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act

            // Assert
            Assert.NotNull(accessTokenClient.RestClient);
        }
示例#7
0
        public void GetUserAccessTokenWithNullPasswordThrowsArgumentNullException()
        {
            // Arrange
            var    accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullPassword      = null;

            // Act

            // Assert
            Assert.Throws <ArgumentNullException>(() => accessTokenClient.GetUserAccessToken(Username, nullPassword, UserScope));
        }
示例#8
0
        public void GetUserAccessTokenCancellationTokenOverloadWithEmptyUsernameThrowsArgumentException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            var emptyUsername     = string.Empty;

            // Act

            // Assert
            Assert.Throws <ArgumentException>(() => accessTokenClient.GetUserAccessToken(emptyUsername, Password, UserScope, CancellationToken.None));
        }
示例#9
0
        public void RefreshTokenCancellationTokenOverloadWithEmptyRefreshTokenThrowsArgumentException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            var emptyRefreshToken = string.Empty;

            // Act

            // Assert
            Assert.Throws <ArgumentException>(() => accessTokenClient.RefreshToken(emptyRefreshToken, CancellationToken.None));
        }
示例#10
0
        public void RefreshTokenCancellationTokenOverloadWithNullRefreshTokenThrowsArgumentNullException()
        {
            // Arrange
            var    accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullRefreshToken  = null;

            // Act

            // Assert
            Assert.Throws <ArgumentNullException>(() => accessTokenClient.RefreshToken(nullRefreshToken, CancellationToken.None));
        }
示例#11
0
        public void GetUserAccessTokenWithEmptyPasswordThrowsArgumentException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            var emptyPassword     = string.Empty;

            // Act

            // Assert
            Assert.Throws <ArgumentException>(() => accessTokenClient.GetUserAccessToken(Username, emptyPassword, UserScope));
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithNullUsernameThrowsArgumentNullException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullUsername = null;

            // Act
            
            // Assert
            Assert.Throws<ArgumentNullException>(() => accessTokenClient.GetUserAccessToken(nullUsername, Password, UserScope, CancellationToken.None));
        }
        public void GetClientAccessTokenCancellationTokenOverloadWithInvalidScopeReturnsAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetClientAccessToken("invalid client scope", CancellationToken.None);

            // Assert
            Assert.Throws <AggregateException>(() => task.Wait());
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithValidCredentialsButInvalidScopeThrowsException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetUserAccessToken(Username, Password, "invalid user scope", CancellationToken.None);

            // Assert
            Assert.Throws <AggregateException>(() => task.Wait());
        }
        public void GetUserAccessTokenWithEmptyUsernameThrowsArgumentException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            var emptyUsername = string.Empty;

            // Act

            // Assert
            Assert.Throws<ArgumentException>(() => accessTokenClient.GetUserAccessToken(emptyUsername, Password, UserScope));
        }
        public void GetClientAccessTokenWithNullScopeDoesNotThrowException()
        {
            // Arrange
            var    accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullScope         = null;

            // Act

            // Assert
            Assert.DoesNotThrow(() => accessTokenClient.GetClientAccessToken(nullScope));
        }
        public void GetUserAccessTokenWithNullScopeDoesNotThrowException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullScope = null;

            // Act

            // Assert
            Assert.DoesNotThrow(() => accessTokenClient.GetUserAccessToken(Username, Password, nullScope));
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithValidCredentialsButInvalidScopeThrowsException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetUserAccessToken(Username, Password, "invalid user scope", CancellationToken.None);

            // Assert
            Assert.Throws<AggregateException>(() => task.Wait());
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithNullScopeDoesNotThrowException()
        {
            // Arrange
            var    accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullScope         = null;

            // Act

            // Assert
            Assert.DoesNotThrow(() => accessTokenClient.GetUserAccessToken(Username, Password, nullScope, CancellationToken.None));
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithValidCredentialsReturnsAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetUserAccessToken(Username, Password, UserScope, CancellationToken.None);
            task.Wait();

            // Assert
            Assert.NotNull(task.Result);
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithValidCredentialsReturnsAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetUserAccessToken(Username, Password, UserScope, CancellationToken.None);

            task.Wait();

            // Assert
            Assert.NotNull(task.Result);
        }
        public void GetClientAccessTokenCancellationTokenOverloadReturnsAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetClientAccessToken(ClientScope, CancellationToken.None);

            task.Wait();

            // Assert
            Assert.NotNull(task.Result);
        }
示例#23
0
        private static async Task <string> GetOAuthToken()
        {
            var clientId     = Environment.GetEnvironmentVariable("clientid");
            var clientSecret = Environment.GetEnvironmentVariable("clientsecret");

            if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
            {
                throw new InvalidOperationException("invalid oauth creds");
            }

            var client      = new AccessTokenClient(AccessTokenClient.ApiDomainBaseAddress);
            var accessToken = await client.Send(clientId, clientSecret);

            return(accessToken.Token);
        }
        public void RefreshTokenCancellationTokenOverloadReturnsNewAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetUserAccessToken(Username, Password, UserScope, CancellationToken.None);

            task.Wait();

            var refreshTokenTask = accessTokenClient.RefreshToken(task.Result.RefreshToken, CancellationToken.None);

            refreshTokenTask.Wait();

            // Assert
            Assert.NotNull(refreshTokenTask.Result);
        }
示例#25
0
        public JsonResult LogOutUserById(string userId)
        {
            bool flag = false;

            if (!string.IsNullOrWhiteSpace(userId))
            {
                Guid uId = new Guid(userId);
                try
                {
                    var cleanTokenResult = 0;
                    using (var client = new AccessTokenClient())
                    {
                        var result = client.RemoveAll(uId, "Setting站点工具登出");
                        result.ThrowIfException(true);
                        cleanTokenResult = result.Result;
                    }
                    if (cleanTokenResult >= 0)
                    {
                        flag = true;
                    }

                    using (var useraccoutClient = new UserAccountClient())
                    {
                        var insertLog = useraccoutClient.LogUserAction(new UserLog
                        {
                            Action      = UserActionEnum.LogOut,
                            CreatedTime = DateTime.Now,
                            UserId      = uId,
                            ChannelIn   = nameof(ChannelIn.H5),
                            Content     = "Setting站点内手动登出该用户"
                        });
                        insertLog.ThrowIfException(true);
                    }
                }
                catch (Exception ex)
                {
                    WebLog.LogException(ex);
                }
            }
            return(Json(flag));
        }
示例#26
0
        public async Task <GetAccessTokenResponse> GetAccessToken(string username, string password, CancellationToken cancellationToken)
        {
            var accessTokenClient = new AccessTokenClient(new OAuthServerConfiguration(_appSettings.Identity.Host, "/auth/token",
                                                                                       _appSettings.Identity.ClientId, _appSettings.Identity.ClientSecret));

            var tokenResponse = await accessTokenClient.GetUserAccessToken(username, password, "", cancellationToken).ConfigureAwait(false);

            if (tokenResponse.IsError)
            {
                return(new GetAccessTokenResponse {
                    AccessToken = null, Error = tokenResponse.Error
                });
            }

            var token = tokenResponse.AccessToken;

            await _accessTokenStore.SaveClientAccessToken(_appSettings.Identity.ClientId, _appSettings.ServiceId,
                                                          token, cancellationToken);

            return(new GetAccessTokenResponse {
                AccessToken = token
            });
        }
        public void RefreshTokenCancellationTokenOverloadReturnsNewAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetUserAccessToken(Username, Password, UserScope, CancellationToken.None);
            task.Wait();

            var refreshTokenTask = accessTokenClient.RefreshToken(task.Result.RefreshToken, CancellationToken.None);
            refreshTokenTask.Wait();

            // Assert
            Assert.NotNull(refreshTokenTask.Result);
        }
        public void GetClientAccessTokenCancellationTokenOverloadReturnsAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetClientAccessToken(ClientScope, CancellationToken.None);
            task.Wait();

            // Assert
            Assert.NotNull(task.Result);
        }
        public void GetClientAccessTokenCancellationTokenOverloadWithInvalidScopeReturnsAccessToken()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);

            // Act
            var task = accessTokenClient.GetClientAccessToken("invalid client scope", CancellationToken.None);

            // Assert
            Assert.Throws<AggregateException>(() => task.Wait());
        }
        public void RefreshTokenCancellationTokenOverloadWithEmptyRefreshTokenThrowsArgumentException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            var emptyRefreshToken = string.Empty;

            // Act

            // Assert
            Assert.Throws<ArgumentException>(() => accessTokenClient.RefreshToken(emptyRefreshToken, CancellationToken.None));
        }
        public void RefreshTokenCancellationTokenOverloadWithNullRefreshTokenThrowsArgumentNullException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullRefreshToken = null;

            // Act

            // Assert
            Assert.Throws<ArgumentNullException>(() => accessTokenClient.RefreshToken(nullRefreshToken, CancellationToken.None));
        }
        public void GetUserAccessTokenCancellationTokenOverloadWithEmptyPasswordThrowsArgumentException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            var emptyPassword = string.Empty;

            // Act

            // Assert
            Assert.Throws<ArgumentException>(() => accessTokenClient.GetUserAccessToken(Username, emptyPassword, UserScope, CancellationToken.None));
        }
        public void GetClientAccessTokenCancellationTokenOverloadWithNullScopeDoesNotThrowException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullScope = null;

            // Act

            // Assert
            Assert.DoesNotThrow(() => accessTokenClient.GetClientAccessToken(nullScope, CancellationToken.None));
        }
示例#34
0
        public async Task <GetAccessTokenResponse> RefreshToken(CancellationToken cancellationToken)
        {
            var tokenResponse = await _accessTokenStore.GetClientAccessToken(_appSettings.Identity.ClientId,
                                                                             _appSettings.ServiceId,
                                                                             cancellationToken).ConfigureAwait(false);

            if (!tokenResponse.HasAccessToken)
            {
                return(new GetAccessTokenResponse {
                    AccessToken = null, Error = tokenResponse.Error
                });
            }

            var token = tokenResponse.AccessToken;

            if (!token.ShouldBeRefreshed(TimeSpan.FromMinutes(2)))
            {
                return new GetAccessTokenResponse {
                           AccessToken = token, Error = null
                }
            }
            ;

            var accessTokenClient = new AccessTokenClient(new OAuthServerConfiguration(
                                                              _appSettings.Identity.Host,
                                                              "/auth/token",
                                                              _appSettings.Identity.ClientId, _appSettings.Identity.ClientSecret));

            try
            {
                var newTokenResponse = await accessTokenClient
                                       .RefreshToken(token.RefreshToken, cancellationToken).ConfigureAwait(false);

                if (newTokenResponse.IsSuccess)
                {
                    var newToken = newTokenResponse.AccessToken;

                    await _accessTokenStore.SaveClientAccessToken(_appSettings.Identity.ClientId,
                                                                  _appSettings.ServiceId,
                                                                  newToken, cancellationToken).ConfigureAwait(false);

                    return(new GetAccessTokenResponse {
                        AccessToken = newToken, Error = null
                    });
                }
                return(new GetAccessTokenResponse
                {
                    AccessToken = null,
                    Error = newTokenResponse.Error
                });
            }
            catch (Exception exception)
            {
                return(new GetAccessTokenResponse
                {
                    AccessToken = null,
                    Error = new ErrorResult
                    {
                        Error = "genericerror",
                        ErrorDescription = exception.Message
                    }
                });
            }
        }
    }
        public void GetUserAccessTokenWithNullPasswordThrowsArgumentNullException()
        {
            // Arrange
            var accessTokenClient = new AccessTokenClient(ServerConfiguration);
            string nullPassword = null;

            // Act

            // Assert
            Assert.Throws<ArgumentNullException>(() => accessTokenClient.GetUserAccessToken(Username, nullPassword, UserScope));
        }
        /// <summary>
        /// 添加微信公众号SDK
        /// </summary>
        /// <param name="serviceDescriptors"></param>
        /// <param name="appId">应用ID</param>
        /// <param name="secret">应用密钥</param>
        /// <param name="isDefault">是否默认,指定默认后,可直接通过WXMPClient从ServiceProvider获取,而无需通过factory</param>
        /// <param name="token">固定token,适合于在调试时,指定固定token</param>
        /// <param name="wxTokenGetter">微信token获取器,如果不直接从微信获取token则可以指定自己的token获取策略</param>
        /// <returns></returns>
        public static IServiceCollection AddWXMPSDK(
            this IServiceCollection serviceDescriptors,
            string appId,
            string secret,
            bool isDefault = true,
            string token   = null,
            Func <ClientCertificateInfo, HttpClient, Task <ClientCertificateToken> > wxTokenGetter = null)
        {
            if (string.IsNullOrEmpty(appId))
            {
                throw new ArgumentNullException(nameof(appId));
            }
            if (string.IsNullOrEmpty(secret))
            {
                throw new ArgumentNullException(nameof(secret));
            }

            Func <ClientCertificateInfo, HttpClient, Task <ClientCertificateToken> > getter = wxTokenGetter;

            if (!string.IsNullOrEmpty(token))
            {
                getter = (c, h) =>
                {
                    return(Task.FromResult(new ClientCertificateToken()
                    {
                        access_token = token,
                        expires_in = 7200
                    }));
                };
            }
            if (getter == null)
            {
                getter = async(client, tokenClient) =>
                {
                    AccessTokenClient atc = new AccessTokenClient(tokenClient);
                    var r = await atc.GetAccessTokenAsync(client.ClientID, client.ClientSecret);

                    if (!string.IsNullOrEmpty(r.AccessToken))
                    {
                        return(new Xfrogcn.AspNetCore.Extensions.ClientCertificateToken()
                        {
                            access_token = r.AccessToken,
                            expires_in = r.ExpiresIn
                        });
                    }
                    return(null);
                };
            }

            serviceDescriptors.TryAddSingleton <FileExtensionContentTypeProvider>();

            serviceDescriptors
            .AddClientTokenProvider(options =>
            {
                options.AddClient(WXConstants.WXMPApiUrl.AbsoluteUri, appId, secret)
                // 获取微信Token
                .SetProcessor(getter)
                // 通过Url QueryString携带Accesstoken
                .SetTokenSetter(SetTokenProcessor.QueryString)
                // 应答检查
                .SetResponseChecker(async(response) =>
                {
                    try
                    {
                        if (checkMediaTypes.Any(mt => response.Content.Headers.ContentType.MediaType.Contains(mt)) &&
                            response.Content.Headers.ContentLength <= 1024 * 2)
                        {
                            var r = await response.GetObjectAsync <WXResponse>(true);
                            //    Console.WriteLine($"{r == null} {response.Content.Headers.ContentType} {response.Content.Headers.ContentLength}");
                            if (r == null || invalidTokenErrCodes.Contains(r.ErrCode))
                            {
                                string responseStr = await response.Content?.ReadAsStringAsync();
                                Console.WriteLine(responseStr);
                                throw new UnauthorizedAccessException("令牌非法");
                            }
                        }
                    }
                    finally
                    {
                    }
                })
                // 使用分布式缓存存储Token
                .SetTokenCacheManager(TokenCacheManager.DistributedCacheFactory);

                //jsapi TICKET
                options.AddClient(WXConstants.WXMPApiUrl.AbsoluteUri, $"JSAPI_{appId}", "NONE")
                // 通过TicketClient获取
                .SetProcessor(new WXCertificateProcessor(appId))
                .SetTokenCacheManager(TokenCacheManager.DistributedCacheFactory);
            });

            // 微信Token处理器
            serviceDescriptors
            .AddHttpClient(appId, client =>
            {
                client.BaseAddress = WXConstants.WXMPApiUrl;
            })
            .AddTokenMessageHandler(appId);

            serviceDescriptors.TryAddSingleton <WXMPClientFactory>();

            if (isDefault)
            {
                serviceDescriptors.TryAddScoped((sp) =>
                {
                    WXMPClientFactory factory = sp.GetRequiredService <WXMPClientFactory>();
                    return(factory.CreateWXClient(appId));
                });
            }

            return(serviceDescriptors);
        }