/// <summary> /// Retrieves the bearer token from cache. /// </summary> /// <param name="authenticationSettings">The authentication settings.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">authenticationSettings.Username /// or /// authenticationSettings.TenantName /// or /// refreshToken</exception> public static AccessTokenResponse RetrieveBearTokenFromCache(Oauth2AuthenticationSettings authenticationSettings) { if (string.IsNullOrEmpty(authenticationSettings.Username)) { throw new ArgumentNullException("authenticationSettings.Username"); } if (string.IsNullOrEmpty(authenticationSettings.TenantName)) { throw new ArgumentNullException("authenticationSettings.TenantName"); } string key = string.Concat("AuthHash:", EncryptionHelper.Md5Encryption.GetMd5Hash(string.Concat(authenticationSettings.TenantName, authenticationSettings.Username))); //Cache Token in Memory var memoryCachingService = new MemoryCacheProvider(); var accessTokenResponse = memoryCachingService.Fetch <AccessTokenResponse>(key); //If token is within the threshold of expiring get refresh token. var timspan = accessTokenResponse.ExpiresOn - DateTime.Now; //if (accessTokenResponse.ExpiresOn >= DateTime.Now - SecurityTokenConstants.TokenLifeTimeEndOfLifeThreshold) if (timspan > new TimeSpan(0, 0, 0, 0) && timspan < SecurityTokenConstants.TokenLifeTimeEndOfLifeThreshold) { accessTokenResponse = RetrieveNewRefreshBearToken(authenticationSettings, accessTokenResponse.RefreshToken); } return(accessTokenResponse); }