public void AddOrReplaceTokenInfo(TeamsTokenType tokenType, TeamsTokenInfo tokenInfo) { PurgeInvalidTokens(); lock (tokens) { if (!tokens.TryGetValue(tokenType, out var tokenInfoList)) { tokenInfoList = new List <TeamsTokenInfo>(); tokens[tokenType] = tokenInfoList; } tokenInfoList.RemoveAll(t => t.Equals(tokenInfo)); tokenInfoList.Add(tokenInfo); } }
private void ExtractToken(string keyAndValue, TeamsTokenType tokenType, Func <string> getUserIdAndTokenPattern, Func <string, string> generateAuthHeader) { var pattern = getUserIdAndTokenPattern(); var matches = Regex.Match(keyAndValue, pattern); if (matches.Success && matches.Groups.Count == 3) { var userId = (TeamsParticipant)matches.Groups[1].Value; if (!userId.IsValid) { logger.Debug("Got user ID {TeamsUserId} via RegEx but it is invalid as per TeamsUserId validity check; ignoring", userId); return; } string token = matches.Groups[2].Value; // \x01{\"skypeToken\":\"THETOKEN\",\"expiration\":1111111111111,\"userDetails\":{\"licenseDetails\":{\"isFreemium\":false,\"isBasicLiveEventsEnabled\":true,\"isTrial\":false,\"isAdvComms\":false},\"regionSettings\":{\"isUnifiedPresenceEnabled\":true,\"isOutOfOfficeIntegrationEnabled\":true,\"isContactMigrationEnabled\":true,\"isAppsDiscoveryEnabled\":true,\"isFederationEnabled\":true},\"region\":\"emea\"}}", var jwtToken = new JwtSecurityToken(token); if (jwtToken.ValidFrom > DateTime.UtcNow || jwtToken.ValidTo < DateTime.UtcNow) { var tenantId = jwtToken.Claims.Where(c => c.Type == "tid").FirstOrDefault()?.Value; logger.Debug("Invalid token, ignoring: Tenant {TenantId}, User {UserId}, {TokenType,25} token (valid from: {ValidFrom}, valid to: {ValidTo})", tenantId.Truncate(Constants.UserIdLogLength, true), userId.Truncate(Constants.UserIdLogLength, true), tokenType, jwtToken.ValidFrom, jwtToken.ValidTo); } else { var authHeaderWithToken = generateAuthHeader(token); var userContext = GetOrCreateUserTokenContext(userId); var tokenInfo = new TeamsTokenInfo(userId, tokenType, token, authHeaderWithToken, jwtToken.ValidFrom, jwtToken.ValidTo); logger.Debug("VALID TOKEN found: {@Token}", tokenInfo); userContext.AddOrReplaceTokenInfo(tokenType, tokenInfo); tokenSource.OnNext(tokenInfo); //var item = cache.Get(tuple); //cache.Set(tuple, authHeaderWithToken, jwtToken.ValidTo - DateTime.UtcNow); } ExtractToken(keyAndValue.Substring(matches.Groups[2].Index + matches.Groups[2].Length), tokenType, getUserIdAndTokenPattern, generateAuthHeader); } }