Example #1
0
        private async Task LoadFromCacheAsync(
            string telemetryId, CacheEvent.TokenTypes type, IAccount account, Action loadingAction)
        {
            var cacheEvent = new CacheEvent(
                CacheEvent.TokenCacheLookup,
                telemetryId)
            {
                TokenType = type
            };

            using (ServiceBundle.TelemetryManager.CreateTelemetryHelper(cacheEvent))
            {
                TokenCacheNotificationArgs args = new TokenCacheNotificationArgs(this, ClientId, account, false);
                await _semaphoreSlim.WaitAsync().ConfigureAwait(false);

                try
                {
                    await OnBeforeAccessAsync(args).ConfigureAwait(false);

                    loadingAction();

                    await OnAfterAccessAsync(args).ConfigureAwait(false);
                }
                finally
                {
                    _semaphoreSlim.Release();
                }
            }
        }
 /// <summary>
 /// Process "HandleRemoteEvent" callback from Java
 /// </summary>
 /// <param name="cacheEvent">com.tridion.cache.CacheEvent</param>
 void ICacheChannelEventListener.HandleRemoteEvent(CacheEvent cacheEvent)
 {
     if (OnRemoteEvent != null)
     {
         OnRemoteEvent(this, new CacheEventArgs(cacheEvent.Region, cacheEvent.Key, cacheEvent.EventType));
     }
 }
Example #3
0
        public static bool UpdatePsw(string userId, string psw, string newPsw, string confirmNewPsw)
        {
            bool flag = string.IsNullOrEmpty(userId);

            if (flag)
            {
                throw new Exception("用户名或密码错误!");
            }
            bool flag2 = newPsw != confirmNewPsw;

            if (flag2)
            {
                throw new Exception("两次输入的密码不匹配!");
            }
            User user  = UserUtils.GetUser(userId);
            bool flag3 = user == null;

            if (flag3)
            {
                throw new Exception("用户名或密码错误!");
            }
            bool disabled = user.Disabled;

            if (disabled)
            {
                throw new Exception("当前用户名已被停用!");
            }
            SystemInfo systemInfo = SystemInfoUtils.GetSystemInfo();
            bool       flag4      = systemInfo != null && systemInfo.PswLength > 0 && systemInfo.PswLength > newPsw.Length;

            if (flag4)
            {
                throw new Exception(string.Format("密码长度小于系统指定最短长度({0})!", systemInfo.PswLength));
            }
            bool flag5 = user.Password != PasswordSec.Encode(userId, psw);

            if (flag5)
            {
                throw new Exception("用户名或密码错误!");
            }
            Database database = LogicContext.GetDatabase();
            HSQL     sql      = new HSQL(database);

            sql.Clear();
            sql.Add("UPDATE USERS SET");
            sql.Add("USERS_PASSWORD = :USERS_PASSWORD");
            sql.Add("WHERE USERS_USERID = :USERS_USERID");
            sql.ParamByName("USERS_PASSWORD").Value = PasswordSec.Encode(userId, newPsw);
            sql.ParamByName("USERS_USERID").Value   = userId;
            bool flag6 = database.ExecSQL(sql) != 1;

            if (flag6)
            {
                throw new Exception(string.Format("用户({0})密码修改失败!", userId));
            }
            CacheEvent.TableIsUpdated("USERS");
            return(true);
        }
Example #4
0
        private void ChangeState(CacheEvent @event, T value = default)
        {
            switch (@event)
            {
            case CacheEvent.Load:
                if (StateChange(CacheState.Pending, CacheState.Loading))
                {
                    this.Load();
                }
                break;

            case CacheEvent.Expire:
                if (StateChange(CacheState.Active, CacheState.Reloading))
                {
                    Task.Run(async() =>
                    {
                        try
                        {
                            await this.Load();
                        }
                        catch (Exception)
                        {
                        }
                    });
                }
                break;

            case CacheEvent.Error:
                // TODO figure out what to do on an error.
                Volatile.Write(ref _currentState, 0);
                break;

            case CacheEvent.Loaded:
                if (StateChange(CacheState.Loading, CacheState.Loaded))
                {
                    Volatile.Write(ref _value, value);
                    Interlocked.MemoryBarrier();     // Need this here to prevent read/write reordering. (LoadStore barrier)
                    Volatile.Write(ref _currentState, (int)CacheState.Active);
                    _stopWatchThreadSafe.Reset();
                    lock (_lock)
                    {
                        foreach (var pendingTask in _pendingTasks)
                        {
                            pendingTask.SetResult(value);
                        }
                        _pendingTasks = new List <TaskCompletionSource <T> >(0);
                    }
                }
                else if (Volatile.Read(ref _currentState) == (int)CacheState.Reloading)
                {
                    // Don't need any ordering here.
                    Volatile.Write(ref _value, value);
                    Volatile.Write(ref _currentState, (int)CacheState.Active);
                    _stopWatchThreadSafe.Reset();
                }
                break;
            }
        }
Example #5
0
        /// <remarks>
        /// Possibly refreshes the internal cache by calling OnBeforeAccessAsync and OnAfterAccessAsync delegates.
        /// </remarks>
        private async Task RefreshCacheForReadOperationsAsync(CacheEvent.TokenTypes cacheEventType)
        {
            if (TokenCacheInternal.IsTokenCacheSerialized())
            {
                if (!_cacheRefreshedForRead)
                {
                    string telemetryId = _requestParams.RequestContext.CorrelationId.AsMatsCorrelationId();
                    var    cacheEvent  = new CacheEvent(CacheEvent.TokenCacheLookup, telemetryId)
                    {
                        TokenType = cacheEventType
                    };

                    await TokenCacheInternal.Semaphore.WaitAsync().ConfigureAwait(false);

                    try
                    {
                        if (!_cacheRefreshedForRead) // double check locking
                        {
                            using (_requestParams.RequestContext.CreateTelemetryHelper(cacheEvent))
                            {
                                string key = SuggestedWebCacheKeyFactory.GetKeyFromRequest(_requestParams);

                                try
                                {
                                    var args = new TokenCacheNotificationArgs(
                                        TokenCacheInternal,
                                        _requestParams.ClientId,
                                        _requestParams.Account,
                                        hasStateChanged: false,
                                        TokenCacheInternal.IsApplicationCache,
                                        hasTokens: TokenCacheInternal.HasTokensNoLocks(),
                                        suggestedCacheKey: key);
                                    await TokenCacheInternal.OnBeforeAccessAsync(args).ConfigureAwait(false);
                                }
                                finally
                                {
                                    var args = new TokenCacheNotificationArgs(
                                        TokenCacheInternal,
                                        _requestParams.ClientId,
                                        _requestParams.Account,
                                        hasStateChanged: false,
                                        TokenCacheInternal.IsApplicationCache,
                                        hasTokens: TokenCacheInternal.HasTokensNoLocks(),
                                        suggestedCacheKey: key);
                                    await TokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);
                                }

                                _cacheRefreshedForRead = true;
                            }
                        }
                    }
                    finally
                    {
                        TokenCacheInternal.Semaphore.Release();
                    }
                }
            }
        }
Example #6
0
        public bool Invoke(CacheEvent evt)
        {
            // Something in the topology has changed. Drop the partition maps to stimulate their re-request on next request
            // Assign primary and backup partition maps to null to force them to be recalculated
            _primaryPartitions = null;
            backupPartitions   = null;

            return(true);
        }
Example #7
0
 private void Update(CacheEvent ev, string key, CacheActionEventArgOrigin origin)
 {
     if (origin == CacheActionEventArgOrigin.Local)
     {
         Interlocked.Increment(ref _updates[ev][0]);
     }
     else
     {
         Interlocked.Increment(ref _updates[ev][1]);
     }
 }
Example #8
0
        // The content of this class has to be placed outside of its base class TokenCacheAccessor,
        // otherwise we would have to modify multiple implementations of TokenCacheAccessor on different platforms.
        public void SaveAccessToken(string cacheKey, string item, RequestContext requestContext)
        {
            var cacheEvent = new CacheEvent(CacheEvent.TokenCacheWrite)
            {
                TokenType = CacheEvent.TokenTypes.AT
            };

            Client.Telemetry.GetInstance().StartEvent(requestContext.TelemetryRequestId, cacheEvent);
            try
            {
                SaveAccessToken(cacheKey, item);
            }
            finally
            {
                Client.Telemetry.GetInstance().StopEvent(requestContext.TelemetryRequestId, cacheEvent);
            }
        }
Example #9
0
        public void DeleteRefreshToken(string cacheKey, RequestContext requestContext)
        {
            var cacheEvent = new CacheEvent(CacheEvent.TokenCacheDelete)
            {
                TokenType = CacheEvent.TokenTypes.RT
            };

            Client.Telemetry.GetInstance().StartEvent(requestContext.TelemetryRequestId, cacheEvent);
            try
            {
                DeleteRefreshToken(cacheKey);
            }
            finally
            {
                Client.Telemetry.GetInstance().StopEvent(requestContext.TelemetryRequestId, cacheEvent);
            }
        }
Example #10
0
        internal RefreshTokenCacheItem FindRefreshToken(AuthenticationRequestParameters requestParams)
        {
            var cacheEvent = new CacheEvent(CacheEvent.TokenCacheLookup)
            {
                TokenType = CacheEvent.TokenTypes.RT
            };

            Telemetry.GetInstance().StartEvent(requestParams.RequestContext.TelemetryRequestId, cacheEvent);
            try
            {
                return(FindRefreshTokenCommon(requestParams));
            }
            finally
            {
                Telemetry.GetInstance().StopEvent(requestParams.RequestContext.TelemetryRequestId, cacheEvent);
            }
        }
Example #11
0
        public void BinaryCacheIsInvalidated()
        {
            MockMessageProvider messageProvider = new MockMessageProvider();

            messageProvider.Start();
            ((DefaultCacheAgent)((FactoryBase)BinaryFactory).CacheAgent).Subscribe(messageProvider);

            ResetImageDimensions();
            TestConfiguration.OverrideBinaryExpiration = 180;
            IBinary binary = BinaryFactory.FindBinary("/media/image.png");

            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            Image img = GetImageFromBytes(binary.BinaryData);

            Assert.IsTrue(img.Width == 320);
            Assert.IsTrue(img.Height == 110);

            ICacheEvent cacheEvent = new CacheEvent()
            {
                Key        = "1:2",
                RegionPath = "Binaries",
                Type       = 0
            };

            messageProvider.BroadcastCacheEvent(cacheEvent);

            // change the generated image dimensions in the provider
            // this should NOT affect the results because the binary should be cached
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageWidth  = 400;
            ((TridionBinaryProvider)BinaryFactory.BinaryProvider).GeneratedImageHeight = 200;

            binary = BinaryFactory.FindBinary("/media/image.png");
            Assert.IsNotNull(binary);
            Assert.IsTrue(binary.BinaryData.Length > 100, "byte array is too small, something went wrong");
            Assert.IsFalse(string.IsNullOrEmpty(binary.Id), "binary.Id is missing");
            img = GetImageFromBytes(binary.BinaryData);
            Assert.IsTrue(img.Width == 400);
            Assert.IsTrue(img.Height == 200);

            ResetImageDimensions();
        }
Example #12
0
        public static bool ResetPsw(string userId, string resetPsw)
        {
            Database database = LogicContext.GetDatabase();
            HSQL     sql      = new HSQL(database);

            sql.Clear();
            sql.Add("UPDATE USERS SET");
            sql.Add("USERS_PASSWORD = :USERS_PASSWORD");
            sql.Add("WHERE USERS_USERID = :USERS_USERID");
            sql.ParamByName("USERS_PASSWORD").Value = PasswordSec.Encode(userId, resetPsw);
            sql.ParamByName("USERS_USERID").Value   = userId;
            bool flag = database.ExecSQL(sql) != 1;

            if (flag)
            {
                throw new Exception(string.Format("用户({0})密码修改失败!", userId));
            }
            CacheEvent.TableIsUpdated("USERS");
            return(true);
        }
Example #13
0
        internal static void Start()
        {
            AppRuntime.AppType     = ((Environment.CurrentDirectory == AppDomain.CurrentDomain.BaseDirectory) ? "WIN" : "WEB");
            AppRuntime.AppSiteName = HostingEnvironment.SiteName;
            AppRuntime.AppRootPath = HostingEnvironment.ApplicationPhysicalPath;
            string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;

            AppRuntime.AppVirtualPath = ((applicationVirtualPath != "/") ? (applicationVirtualPath + "/") : applicationVirtualPath);
            AppRuntime.AppBit         = ((IntPtr.Size != 4) ? ((IntPtr.Size != 8) ? AppBitType.None : AppBitType.Bit64) : AppBitType.Bit32);
            AppRuntime.MachineName    = Environment.MachineName;
            Environment.SetEnvironmentVariable("NLS_LANG", "SIMPLIFIED CHINESE_CHINA.ZHS16GBK");
            Environment.SetEnvironmentVariable("NLS_DATE_FORMAT", "YYYY-MM-DD HH24:MI:SS");
            Environment.SetEnvironmentVariable("NLS_TIMESTAMP_FORMAT", "YYYY-MM-DD HH24:MI:SS");
            string str  = AppConfig.TNS_ADMIN;
            bool   flag = !string.IsNullOrEmpty(str);

            if (flag)
            {
                Environment.SetEnvironmentVariable("TNS_ADMIN", str);
            }
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AppRuntime.CurrentDomain_AssemblyResolve);
            AppRuntime._DbQueryDateTime              = AppUtils.GetDbServerDateTime();
            AppRuntime.ServerDateTime = AppRuntime._DbQueryDateTime;
            try
            {
                ComponentInit.Init();
                UsersInit.Init();
                TIM.T_KERNEL.SystemInit.SystemInit.Init();
                PermissionOpInit.Init();
                CacheEvent.UpdateUCache();
            }
            catch (Exception ex)
            {
                AppEventLog.Error("AppRuntime 异常" + ex.Message);
            }
            TimerManager.Initialize();
            TimerManager.Instance.AddTask(TimerCategory.SessionTask, "AUTHSESSION", typeof(AuthSessionUpdateTask), string.Empty, string.Empty);
            TimerManager.Instance.AddTask(TimerCategory.SessionTask, "MEMORYSESSION", typeof(UCacheUpdateTask), string.Empty, string.Empty);
            TimerManager.Instance.AddTask(TimerCategory.TableCacheTask, "TABLECACHE", typeof(UCacheUpdateTask), string.Empty, string.Empty);
            TimerManager.Instance.AddTask(TimerCategory.TimeModuleTask, "TIMEMODULE", typeof(JobScheduleTask), AppConfig.DefaultDbId, "ADMIN");
        }
Example #14
0
        private async Task RefreshCacheForReadOperationsAsync(CacheEvent.TokenTypes cacheEventType)
        {
            if (!_cacheRefreshedForRead)
            {
                string telemetryId = _requestParams.RequestContext.CorrelationId.AsMatsCorrelationId();
                var    cacheEvent  = new CacheEvent(CacheEvent.TokenCacheLookup, telemetryId)
                {
                    TokenType = cacheEventType
                };

                await TokenCacheInternal.Semaphore.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (!_cacheRefreshedForRead) // double check locking
                    {
                        using (_telemetryManager.CreateTelemetryHelper(cacheEvent))
                        {
                            TokenCacheNotificationArgs args = new TokenCacheNotificationArgs(
                                TokenCacheInternal,
                                _requestParams.ClientId,
                                _requestParams.Account,
                                hasStateChanged: false,
                                TokenCacheInternal.IsApplicationCache);

                            await TokenCacheInternal.OnBeforeAccessAsync(args).ConfigureAwait(false);

                            await TokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);

                            _cacheRefreshedForRead = true;
                        }
                    }
                }
                finally
                {
                    TokenCacheInternal.Semaphore.Release();
                }
            }
        }
        public void TelemetryEventCountsAreCorrectTest()
        {
            string[] reqIdArray = new string[5];
            Task[]   taskArray  = new Task[5];
            try
            {
                for (int i = 0; i < 5; i++)
                {
                    var correlationId = Guid.NewGuid().AsMatsCorrelationId();
                    reqIdArray[i] = correlationId;
                    Task task = new Task(() =>
                    {
                        var e1 = new ApiEvent(_logger, _crypto, correlationId)
                        {
                            Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad"
                        };
                        _telemetryManager.StartEvent(e1);
                        // do some stuff...
                        e1.WasSuccessful = true;
                        _telemetryManager.StopEvent(e1);

                        var e2 = new HttpEvent(correlationId)
                        {
                            HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2"
                        };
                        _telemetryManager.StartEvent(e2);
                        // do some stuff...
                        e2.HttpResponseStatus = 200;
                        _telemetryManager.StopEvent(e2);

                        var e3 = new HttpEvent(correlationId)
                        {
                            HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeOtherUserAgent", QueryParams = "?a=3&b=4"
                        };
                        _telemetryManager.StartEvent(e3);
                        // do some stuff...
                        e2.HttpResponseStatus = 200;
                        _telemetryManager.StopEvent(e3);

                        var e4 = new CacheEvent(CacheEvent.TokenCacheWrite, correlationId)
                        {
                            TokenType = CacheEvent.TokenTypes.AT
                        };
                        _telemetryManager.StartEvent(e4);
                        // do some stuff...
                        _telemetryManager.StopEvent(e4);

                        var e5 = new CacheEvent(CacheEvent.TokenCacheDelete, correlationId)
                        {
                            TokenType = CacheEvent.TokenTypes.RT
                        };
                        _telemetryManager.StartEvent(e5);
                        // do some stuff...
                        _telemetryManager.StopEvent(e5);
                    });
                    taskArray[i] = task;
                    task.Start();
                }
                Task.WaitAll(taskArray);
            }
            finally
            {
                foreach (string reqId in reqIdArray)
                {
                    _telemetryManager.Flush(reqId);
                }
            }
            // Every task should have one default event with these counts
            foreach (Dictionary <string, string> telemetryEvent in _myReceiver.EventsReceived)
            {
                if (telemetryEvent[EventBase.EventNameKey] == "msal.default_event")
                {
                    Assert.AreEqual("2", telemetryEvent[MsalTelemetryBlobEventNames.HttpEventCountTelemetryBatchKey]);
                    Assert.AreEqual("2", telemetryEvent[MsalTelemetryBlobEventNames.CacheEventCountConstStrKey]);
                    Assert.AreEqual("0", telemetryEvent[MsalTelemetryBlobEventNames.UiEventCountTelemetryBatchKey]);
                }
            }
        }
Example #16
0
        private static void TestBackplaneEvent <TEventArgs>(
            CacheEvent cacheEvent,
            Action <ICacheManager <object> > arrange,
            Action <ICacheManager <object>, TEventArgs> assertLocal,
            Action <ICacheManager <object>, TEventArgs> assertRemote)
            where TEventArgs : EventArgs
        {
            var       channelName          = Guid.NewGuid().ToString();
            var       cacheA               = TestManagers.CreateRedisAndDicCacheWithBackplane(1, false, channelName);
            var       cacheB               = TestManagers.CreateRedisAndDicCacheWithBackplane(1, false, channelName);
            var       eventTriggeredLocal  = 0;
            var       eventTriggeredRemote = 0;
            Exception lastError            = null;

            Action <EventArgs> testLocal = (args) =>
            {
                try
                {
                    assertLocal(cacheA, (TEventArgs)args);

                    Interlocked.Increment(ref eventTriggeredLocal);
                }
                catch (Exception ex)
                {
                    lastError = ex;
                    throw;
                }
            };

            Action <EventArgs> testRemote = (args) =>
            {
                try
                {
                    assertRemote(cacheB, (TEventArgs)args);

                    Interlocked.Increment(ref eventTriggeredRemote);
                }
                catch (Exception ex)
                {
                    lastError = ex;
                    throw;
                }
            };

            switch (cacheEvent)
            {
            case CacheEvent.OnAdd:
                cacheA.OnAdd += (ev, args) =>
                {
                    testLocal(args);
                };

                cacheB.OnAdd += (ev, args) =>
                {
                    testRemote(args);
                };
                break;

            case CacheEvent.OnClear:
                cacheA.OnClear += (ev, args) =>
                {
                    testLocal(args);
                };

                cacheB.OnClear += (ev, args) =>
                {
                    testRemote(args);
                };
                break;

            case CacheEvent.OnClearRegion:
                cacheA.OnClearRegion += (ev, args) =>
                {
                    testLocal(args);
                };

                cacheB.OnClearRegion += (ev, args) =>
                {
                    testRemote(args);
                };
                break;

            case CacheEvent.OnPut:
                cacheA.OnPut += (ev, args) =>
                {
                    testLocal(args);
                };

                cacheB.OnPut += (ev, args) =>
                {
                    testRemote(args);
                };
                break;

            case CacheEvent.OnRemove:
                cacheA.OnRemove += (ev, args) =>
                {
                    testLocal(args);
                };

                cacheB.OnRemove += (ev, args) =>
                {
                    testRemote(args);
                };
                break;

            case CacheEvent.OnUpdate:
                cacheA.OnUpdate += (ev, args) =>
                {
                    testLocal(args);
                };

                cacheB.OnUpdate += (ev, args) =>
                {
                    testRemote(args);
                };
                break;
            }

            arrange(cacheA);

            Func <int, Func <bool>, bool> waitForIt = (tries, act) =>
            {
                var i      = 0;
                var result = false;
                while (!result && i < tries)
                {
                    i++;
                    result = act();
                    if (result)
                    {
                        return(true);
                    }

                    Thread.Sleep(100);
                }

                return(false);
            };

            Func <Exception, string> formatError = (err) =>
            {
                var xunitError = err as XunitException;
                if (xunitError != null)
                {
                    return(xunitError.Message);
                }

                return(err?.ToString());
            };

            var triggerResult = waitForIt(100, () => eventTriggeredRemote == 1);

            lastError.Should().BeNull(formatError(lastError));
            triggerResult.Should().BeTrue("Event should get triggered through the backplane.");
            eventTriggeredLocal.Should().Be(1, "Local cache event should be triggered one time");
        }
Example #17
0
 private void Update(CacheEvent ev, string key)
 {
     Interlocked.Increment(ref _updates[ev][0]);
 }
Example #18
0
        public void TelemetryEventCountsAreCorrectTest()
        {
            string[] reqIdArray = new string[5];
            Task[]   taskArray  = new Task[5];
            try
            {
                for (int i = 0; i < 5; i++)
                {
                    string reqId = _telemetryManager.GenerateNewRequestId();
                    reqIdArray[i] = reqId;
                    Task task = new Task(() =>
                    {
                        var e1 = new ApiEvent(new MsalLogger(Guid.NewGuid(), null))
                        {
                            Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad"
                        };
                        _telemetryManager.StartEvent(reqId, e1);
                        // do some stuff...
                        e1.WasSuccessful = true;
                        _telemetryManager.StopEvent(reqId, e1);

                        var e2 = new HttpEvent()
                        {
                            HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2"
                        };
                        _telemetryManager.StartEvent(reqId, e2);
                        // do some stuff...
                        e2.HttpResponseStatus = 200;
                        _telemetryManager.StopEvent(reqId, e2);

                        var e3 = new HttpEvent()
                        {
                            HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeOtherUserAgent", QueryParams = "?a=3&b=4"
                        };
                        _telemetryManager.StartEvent(reqId, e3);
                        // do some stuff...
                        e2.HttpResponseStatus = 200;
                        _telemetryManager.StopEvent(reqId, e3);

                        var e4 = new CacheEvent(CacheEvent.TokenCacheWrite)
                        {
                            TokenType = CacheEvent.TokenTypes.AT
                        };
                        _telemetryManager.StartEvent(reqId, e4);
                        // do some stuff...
                        _telemetryManager.StopEvent(reqId, e4);

                        var e5 = new CacheEvent(CacheEvent.TokenCacheDelete)
                        {
                            TokenType = CacheEvent.TokenTypes.RT
                        };
                        _telemetryManager.StartEvent(reqId, e5);
                        // do some stuff...
                        _telemetryManager.StopEvent(reqId, e5);
                    });
                    taskArray[i] = task;
                    task.Start();
                }
                Task.WaitAll(taskArray);
            }
            finally
            {
                foreach (string reqId in reqIdArray)
                {
                    _telemetryManager.Flush(reqId, ClientId);
                }
            }
            // Every task should have one default event with these counts
            foreach (Dictionary <string, string> telemetryEvent in _myReceiver.EventsReceived)
            {
                if (telemetryEvent[EventBase.EventNameKey] == TelemetryEventProperties.MsalDefaultEvent)
                {
                    Assert.AreEqual("2", telemetryEvent[TelemetryEventProperties.MsalHttpEventCount]);
                    Assert.AreEqual("2", telemetryEvent[TelemetryEventProperties.MsalCacheEventCount]);
                    Assert.AreEqual("0", telemetryEvent[TelemetryEventProperties.MsalUiEventCount]);
                }
            }
        }
 public override void cacheItemUpdated(CacheEvent ce)
 {
     Console.WriteLine("Cache: An item is updated");
 }
 public override void cacheItemRemoved(CacheEvent ce)
 {
     Console.WriteLine("Cache: An item is removed");
 }
 public EntityCacheEvent(string entity, CacheEvent cacheevent)
 {
     Entity = entity;
     Event  = cacheevent;
 }
Example #22
0
        async Task <MsalRefreshTokenCacheItem> ITokenCacheInternal.FindRefreshTokenAsync(
            AuthenticationRequestParameters requestParams,
            string familyId)
        {
            var cacheEvent = new CacheEvent(
                CacheEvent.TokenCacheLookup,
                requestParams.RequestContext.TelemetryCorrelationId)
            {
                TokenType = CacheEvent.TokenTypes.RT
            };

            using (ServiceBundle.TelemetryManager.CreateTelemetryHelper(cacheEvent))
            {
                if (requestParams.Authority == null)
                {
                    return(null);
                }

                var instanceDiscoveryMetadataEntry = await GetCachedOrDiscoverAuthorityMetaDataAsync(
                    requestParams.AuthorityInfo.CanonicalAuthority,
                    requestParams.RequestContext).ConfigureAwait(false);

                var environmentAliases = GetEnvironmentAliases(
                    requestParams.AuthorityInfo.CanonicalAuthority,
                    instanceDiscoveryMetadataEntry);

                var preferredEnvironmentHost = GetPreferredEnvironmentHost(
                    requestParams.AuthorityInfo.Host,
                    instanceDiscoveryMetadataEntry);

                await _semaphoreSlim.WaitAsync().ConfigureAwait(false);

                try
                {
                    requestParams.RequestContext.Logger.Info("Looking up refresh token in the cache..");

                    TokenCacheNotificationArgs args = new TokenCacheNotificationArgs(this, ClientId, requestParams.Account, false);

                    // make sure to check preferredEnvironmentHost first
                    var allEnvAliases = new List <string>()
                    {
                        preferredEnvironmentHost
                    };
                    allEnvAliases.AddRange(environmentAliases);

                    var keysAcrossEnvs = allEnvAliases.Select(ea => new MsalRefreshTokenCacheKey(
                                                                  ea,
                                                                  requestParams.ClientId,
                                                                  requestParams.Account?.HomeAccountId?.Identifier,
                                                                  familyId));

                    await OnBeforeAccessAsync(args).ConfigureAwait(false);

                    try
                    {
                        // Try to load from all env aliases, but stop at the first valid one
                        MsalRefreshTokenCacheItem msalRefreshTokenCacheItem = keysAcrossEnvs
                                                                              .Select(key => _accessor.GetRefreshToken(key))
                                                                              .FirstOrDefault(item => item != null);

                        requestParams.RequestContext.Logger.Info("Refresh token found in the cache? - " + (msalRefreshTokenCacheItem != null));

                        if (msalRefreshTokenCacheItem != null)
                        {
                            return(msalRefreshTokenCacheItem);
                        }

                        requestParams.RequestContext.Logger.Info("Checking ADAL cache for matching RT");

                        string upn = string.IsNullOrWhiteSpace(requestParams.LoginHint)
                            ? requestParams.Account?.Username
                            : requestParams.LoginHint;

                        // ADAL legacy cache does not store FRTs
                        if (requestParams.Account != null && string.IsNullOrEmpty(familyId))
                        {
                            return(CacheFallbackOperations.GetAdalEntryForMsal(
                                       Logger,
                                       LegacyCachePersistence,
                                       preferredEnvironmentHost,
                                       environmentAliases,
                                       requestParams.ClientId,
                                       upn,
                                       requestParams.Account.HomeAccountId?.Identifier));
                        }

                        return(null);
                    }
                    finally
                    {
                        await OnAfterAccessAsync(args).ConfigureAwait(false);
                    }
                }
                finally
                {
                    _semaphoreSlim.Release();
                }
            }
        }
        /// <remarks>
        /// Possibly refreshes the internal cache by calling OnBeforeAccessAsync and OnAfterAccessAsync delegates.
        /// </remarks>
        private async Task RefreshCacheForReadOperationsAsync(CacheEvent.TokenTypes cacheEventType)
        {
            if (TokenCacheInternal.IsTokenCacheSerialized())
            {
                if (!_cacheRefreshedForRead)
                {
                    var cacheEvent = new CacheEvent(CacheEvent.TokenCacheLookup, _requestParams.RequestContext.CorrelationId.AsMatsCorrelationId())
                    {
                        TokenType = cacheEventType
                    };

                    _requestParams.RequestContext.Logger.Verbose("[Cache Session Manager] Waiting for cache semaphore");
                    await TokenCacheInternal.Semaphore.WaitAsync().ConfigureAwait(false);

                    _requestParams.RequestContext.Logger.Verbose("[Cache Session Manager] Entered cache semaphore");

                    Stopwatch stopwatch = new Stopwatch();
                    try
                    {
                        if (!_cacheRefreshedForRead) // double check locking
                        {
                            using (_requestParams.RequestContext.CreateTelemetryHelper(cacheEvent))
                            {
                                string key = SuggestedWebCacheKeyFactory.GetKeyFromRequest(_requestParams);

                                try
                                {
                                    var args = new TokenCacheNotificationArgs(
                                        TokenCacheInternal,
                                        _requestParams.AppConfig.ClientId,
                                        _requestParams.Account,
                                        hasStateChanged: false,
                                        TokenCacheInternal.IsApplicationCache,
                                        hasTokens: TokenCacheInternal.HasTokensNoLocks(),
                                        _requestParams.RequestContext.UserCancellationToken,
                                        suggestedCacheKey: key);

                                    stopwatch.Start();
                                    await TokenCacheInternal.OnBeforeAccessAsync(args).ConfigureAwait(false);

                                    RequestContext.ApiEvent.DurationInCacheInMs += stopwatch.ElapsedMilliseconds;
                                }
                                finally
                                {
                                    var args = new TokenCacheNotificationArgs(
                                        TokenCacheInternal,
                                        _requestParams.AppConfig.ClientId,
                                        _requestParams.Account,
                                        hasStateChanged: false,
                                        TokenCacheInternal.IsApplicationCache,
                                        hasTokens: TokenCacheInternal.HasTokensNoLocks(),
                                        _requestParams.RequestContext.UserCancellationToken,
                                        suggestedCacheKey: key);

                                    stopwatch.Reset();
                                    stopwatch.Start();
                                    await TokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);

                                    RequestContext.ApiEvent.DurationInCacheInMs += stopwatch.ElapsedMilliseconds;
                                }

                                _cacheRefreshedForRead = true;
                            }
                        }
                    }
                    finally
                    {
                        TokenCacheInternal.Semaphore.Release();
                        _requestParams.RequestContext.Logger.Verbose("[Cache Session Manager] Released cache semaphore");
                    }
                }
            }
        }
Example #24
0
 public override bool InsertComplete(HSQL hsql)
 {
     CacheEvent.TableIsUpdated("REPORTSTYLE");
     return(base.InsertComplete(hsql));
 }