public void Test2()
        {
            var token = new AuthorizationToken()
            {
                Id      = "token-1",
                Expires = DateTime.Parse("2021-01-01 12:44:45")
            };

            var key = Encoding.UTF8.GetBytes("1234567890");

            var session = token.IssueTokenAsBase64String(key);


            var(result, baseToken) = TokensManager.ParseBase64Token <AuthorizationToken>(session, key, token.Expires.AddSeconds(-1));

            Assert.AreEqual(TokenParseResult.Ok, result);

            Assert.AreEqual(token.Id, baseToken.Id);
            Assert.AreEqual(token.Expires, baseToken.Expires);

            var(result2, newToken) = TokensManager.ParseBase64Token <JetWalletToken>(session, key, token.Expires.AddSeconds(-1));
            Assert.AreEqual(TokenParseResult.Ok, result2);

            Assert.AreEqual(token.Id, newToken.Id);
            Assert.AreEqual(token.Expires, newToken.Expires);
            Assert.AreEqual(null, newToken.BrandId);
            Assert.AreEqual(null, newToken.BrokerId);
            Assert.AreEqual(null, newToken.SessionRootId);

            var(result3, newToken2) = TokensManager.ParseBase64Token <JetWalletToken>(session, key, token.Expires);
            Assert.AreEqual(TokenParseResult.Expired, result3);
        }
        public void TTtt()
        {
            var session = "phh8Sc2vLgde4Ds9aeQY5eaXzjN7FImLCFvE3TDwC8wXlcvwKQ5Ns0soZ/BPxwZzNUBnbyac/ElkpFg/sxKhYyMzceEr/aYNvW1TkAgQmu1quaXumfgREix0RCEo4iqjAEgJnoaivND8WpoBp0HyOkSLM6Z5xsxSOu0ID6EikVXn8xNrJY7run4w9/ZYa88Z";

            var(result, baseToken) = TokensManager.ParseBase64Token <JetWalletToken>(session, Encoding.UTF8.GetBytes("e537d941-f7d2-4939-b97b-ae4722ca56aa"), DateTime.UtcNow);

            Console.WriteLine(result);
        }
        public void TTtt2()
        {
            var session = "u4uVXItnwcLG0rdTULo7LotsqiQNw1DbpvIkLCEMnG8xb9lREXY5h4GRlOiIiaFipKTZw7oS0KkZuryJrj0L4x1uG3hMDtBLY2yRQ/hsEX478wIr5gePCEltZ5H49WyLivLu2uxL1DmTAbDPQjKknPM+xlXz4kXSDZ7ZJz88LOMNUE8tMRp73R/2uINRUBZK5w+Xbw8Yz9Bii7RQLvM+RZBLLzPr9I0mi4o6UvDOXmmtLyoJeoQU5+iZgJ9tdzHJtEAaLCyWlBx1At0u6E+llA==";

            var(result, baseToken) = TokensManager.ParseBase64Token <JetWalletToken>(session, Encoding.UTF8.GetBytes("e537d941-f7d2-4939-b97b-ae4722ca56aa"), DateTime.UtcNow);

            Console.WriteLine(result);

            Console.WriteLine(JsonConvert.SerializeObject(baseToken));
        }
        public async Task <AuthorizationResponse> AuthorizationAsync(AuthorizationRequest request)
        {
            using var activity = MyTelemetry.StartActivity("Authorization base on session token");

            if (string.IsNullOrEmpty(request.Token) ||
                string.IsNullOrEmpty(request.BrandId) ||
                string.IsNullOrEmpty(request.BrokerId))
            {
                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            var(result, baseToken) = TokensManager.ParseBase64Token <JetWalletToken>(request.Token, AuthConst.GetSessionEncodingKey(), DateTime.UtcNow);

            if (result != TokenParseResult.Ok)
            {
                activity.SetStatus(Status.Error);
                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            if (!string.IsNullOrEmpty(baseToken.SessionRootId))
            {
                _logger.LogWarning("Cannot Authorization session base on token with existing RootSession: {rootIdText}", baseToken.SessionRootId);
                activity.SetStatus(Status.Error);
                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            var token = new JetWalletToken()
            {
                Id            = baseToken.Id,
                Expires       = DateTime.UtcNow.AddMinutes(_settings.SessionLifeTimeMinutes),
                SessionRootId = Guid.NewGuid().ToString("N"),
                SessionId     = Guid.NewGuid().ToString("N"),
                BrandId       = request.BrandId,
                BrokerId      = request.BrokerId
            };

            token.Id.AddToActivityAsTag("clientId");
            token.BrokerId.AddToActivityAsTag("brokerId");
            token.BrandId.AddToActivityAsTag("brandId");

            token.SessionRootId.AddToActivityAsTag("sessionRootId");


            var clientIdentity = new JetClientIdentity(request.BrokerId, request.BrandId, baseToken.Id);
            var response       = await _clientRegistrationService.GetOrRegisterClientAsync(clientIdentity);

            if (response.Result != ClientRegistrationResponse.RegistrationResult.Ok)
            {
                _logger.LogError("Cannot register client. Client already register with another brand. BrokerId/BrandId/ClientId: {brokerId}/{brandId}/{clientId}",
                                 clientIdentity.BrokerId, clientIdentity.BrandId, clientIdentity.ClientId);

                activity.SetStatus(Status.Error);
                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            ClientWallet wallet  = null;
            var          wallets = await _clientWalletService.GetWalletsByClient(clientIdentity);

            if (string.IsNullOrEmpty(request.WalletId))
            {
                wallet = wallets?.Wallets?.FirstOrDefault(w => w.IsDefault) ?? wallets?.Wallets?.FirstOrDefault();
            }
            else
            {
                wallet = wallets?.Wallets?.FirstOrDefault(w => w.WalletId == request.WalletId);
            }

            if (wallet == null)
            {
                request.WalletId.AddToActivityAsTag("walletId");
                _logger.LogWarning("Cannot Authorization session, wallet do not found. WalletId {walletId}. ClientId: {clientId}", request.WalletId, token.Id);
                activity.SetStatus(Status.Error);
                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            token.WalletId = wallet.WalletId;
            token.WalletId.AddToActivityAsTag("walletId");

            var session = token.IssueTokenAsBase64String(AuthConst.GetSessionEncodingKey());

            var dueData   = DateTime.UtcNow.AddHours(_settings.RootSessionLifeTimeHours);
            var publicKey = MyRsa.ReadPublicKeyFromPem(request.PublicKeyPem);

            var entity = SpotSessionNoSql.Create(request.BrokerId, request.BrandId, baseToken.Id, dueData, publicKey, token.SessionRootId);
            await _writer.InsertOrReplaceAsync(entity);

            await _sessionAuditService.NewSessionAudit(baseToken, token, request.UserAgent, request.Ip);

            _logger.LogInformation("Session Authorization is success. RootSessionId: {rootIdText}. ClientId:{clientId}", token.SessionRootId, token.ClientId());

            return(new AuthorizationResponse()
            {
                Result = true,
                Token = session
            });
        }
        public async Task <AuthorizationResponse> RefreshSessionAsync(RefreshSessionRequest request)
        {
            using var activity = MyTelemetry.StartActivity("Refresh Session");

            if (string.IsNullOrEmpty(request.Token) || string.IsNullOrEmpty(request.SignatureBase64))
            {
                activity.AddTag("message", "bad request");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            if (DateTime.UtcNow < request.RequestTimestamp || request.RequestTimestamp < DateTime.UtcNow.AddSeconds(-_settings.RequestTimeLifeSec))
            {
                activity.AddTag("message", "request expired");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            var(result, token) = TokensManager.ParseBase64Token <JetWalletToken>(request.Token, AuthConst.GetSessionEncodingKey(), DateTime.UtcNow);

            if (result != TokenParseResult.Ok && result != TokenParseResult.Expired)
            {
                activity.AddTag("message", "wrong token");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            token.Id.AddToActivityAsTag("clientId");
            token.BrokerId.AddToActivityAsTag("brokerId");
            token.BrandId.AddToActivityAsTag("brandId");
            token.WalletId.AddToActivityAsTag("walletId");
            token.SessionRootId.AddToActivityAsTag("sessionRootId");

            var entity = await _writer.GetAsync(SpotSessionNoSql.GeneratePartitionKey(token.ClientId()), SpotSessionNoSql.GenerateRowKey(token.SessionRootId));

            if (entity == null)
            {
                activity.AddTag("message", "root session do not exist");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            if (DateTime.UtcNow >= entity.DiedDateTime)
            {
                activity.AddTag("message", "root session is died");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            if (DateTime.UtcNow <= entity.CreateDateTime.AddSeconds(_settings.TimeoutToRefreshNewSessionInSec))
            {
                activity.AddTag("message", "the session is very young, for renewal");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            var signContent     = $"{request.Token}_{request.RequestTimestamp:yyyy-MM-ddTHH:mm:ss}_{request.NewWalletId}";
            var verifySignature = MyRsa.ValidateSignature(signContent, request.SignatureBase64, entity.PublicKeyBase64);

            if (!verifySignature)
            {
                activity.AddTag("message", "wrong signature");
                activity.SetStatus(Status.Error);

                return(new AuthorizationResponse()
                {
                    Result = false
                });
            }

            var walletId = token.WalletId;

            if (!string.IsNullOrEmpty(request.NewWalletId))
            {
                var clientIdentity = new JetClientIdentity(token.BrokerId, token.BrandId, token.Id);
                var wallets        = await _clientWalletService.GetWalletsByClient(clientIdentity);

                var wallet = wallets?.Wallets?.FirstOrDefault(w => w.WalletId == request.NewWalletId);

                if (wallet == null)
                {
                    request.NewWalletId.AddToActivityAsTag("walletId");
                    _logger.LogWarning("Cannot Refresh session, NewWallet do not found. WalletId {walletId}. ClientId: {clientId}", request.NewWalletId, token.Id);
                    activity.SetStatus(Status.Error);
                    return(new AuthorizationResponse()
                    {
                        Result = false
                    });
                }

                walletId = wallet.WalletId;
                _logger.LogInformation("Client update session to new walletId. SessionRootId: {sessionRootId}; ClientId: {clientId}; WalletId: {walletId}",
                                       token.SessionRootId, token.Id, walletId);
            }

            walletId.AddToActivityAsTag("walletId");

            var newToken = new JetWalletToken()
            {
                Id            = token.Id,
                Expires       = DateTime.UtcNow.AddMinutes(_settings.SessionLifeTimeMinutes),
                SessionRootId = token.SessionRootId,
                SessionId     = Guid.NewGuid().ToString("N"),
                BrandId       = token.BrandId,
                BrokerId      = token.BrokerId,
                WalletId      = walletId
            };

            await _sessionAuditService.RefreshSessionAudit(token, newToken, request.UserAgent, request.Ip);

            _logger.LogInformation("Refresh session is success. SessionRootId: {sessionRootId}; SessionId: {sessionId}; PrevSessionId: {prevSessionId}; ClientId: {clientId}; WalletId: {walletId}",
                                   newToken.SessionRootId, newToken.SessionId, token.SessionId, newToken.ClientId(), newToken.WalletId);

            return(new AuthorizationResponse()
            {
                Token = newToken.IssueTokenAsBase64String(AuthConst.GetSessionEncodingKey()),
                Result = true
            });
        }