예제 #1
0
        /// <summary>
        /// Decode cache contents into something we can feed to AuthenticationResult.Deserialize.
        /// WARNING: This will be deprecated eventually by ADAL team and replaced by something supported.
        /// </summary>
        /// <param name="key">The cache key for the entry to decode</param>
        /// <returns>The decoded string to pass to AuthenticationResult.Deserialize</returns>
        private AuthenticationResult DecodeCachedAuthResult(TokenCacheKey key)
        {
            string encoded = tokenCache[key];
            string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));

            return(AuthenticationResult.Deserialize(decoded));
        }
예제 #2
0
        public static void DumpTokenCache()
        {
            var tokenCache  = TokenCache.GetCache();
            var tenantCache = TenantCache.GetCache();

            if (tokenCache.Count > 0)
            {
                foreach (var value in tokenCache.Values.ToArray())
                {
                    var authResult = AuthenticationResult.Deserialize(Encoding.UTF8.GetString(Convert.FromBase64String(value)));
                    var tenantId   = authResult.TenantId;

                    if (InfrastructureTenantIds.Contains(tenantId))
                    {
                        continue;
                    }

                    var user    = authResult.UserInfo.UserId;
                    var details = tenantCache[tenantId];
                    Console.WriteLine("User: {0}, Tenant: {1} {2} ({3})", user, tenantId, details.displayName, details.domain);

                    var subscriptions = details.subscriptions;
                    Console.WriteLine("\tThere are {0} subscriptions", subscriptions.Length);

                    foreach (var subscription in subscriptions)
                    {
                        Console.WriteLine("\tSubscription {0} ({1})", subscription.subscriptionId, subscription.displayName);
                    }
                    Console.WriteLine();
                }
            }
        }
예제 #3
0
        public static async Task <AuthenticationResult> GetRecentToken()
        {
            var recentTokenFile = GetRecentTokenFile();
            var authResult      = AuthenticationResult.Deserialize(ProtectedFile.ReadAllText(recentTokenFile));

            if (!String.IsNullOrEmpty(authResult.RefreshToken) && authResult.ExpiresOn <= DateTime.UtcNow)
            {
                var tokenCache = TokenCache.GetCache();
                authResult = await GetAuthorizationResult(tokenCache, authResult.TenantId, authResult.UserInfo.UserId);

                TokenCache.SaveCache(tokenCache);
                SaveRecentToken(authResult);
            }

            return(authResult);
        }
예제 #4
0
        protected bool TryAcquireToken(out string token)
        {
            token = string.Empty;

            if (!File.Exists(TOKEN_CACHE_FIIE))
            {
                return(false);
            }

            var text = File.ReadAllText(TOKEN_CACHE_FIIE);

            var authenticationResult = AuthenticationResult.Deserialize(text);

            if (authenticationResult.ExpiresOn < DateTime.Now)
            {
                return(false);
            }

            token = authenticationResult.AccessToken;

            return(true);
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <Message> Post([FromBody] Message message)
        {
            #region Check Authorization
            try
            {
                string d = (string)message.BotUserData;
                AuthenticationResult  ar = AuthenticationResult.Deserialize(d);
                AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
                ar = DateTimeOffset.Compare(DateTimeOffset.Now, ar.ExpiresOn) < 0 ? ar : await ac.AcquireTokenByRefreshTokenAsync(ar.RefreshToken, new ClientCredential(Constants.ADClientId, Constants.ADClientSecret));
            }
            catch (Exception ex)
            {
                return(message.CreateReplyMessage($"You must authenticate to use bot: https://jehollanVSBot.azurewebsites.net/api/{message.From.Id}/login"));
            }

            #endregion

            if (message.Type == "Message")
            {
                #region bot /commands
                if (Regex.IsMatch(message.Text, Constants.regex_command))
                {
                    string command = Regex.Match(message.Text, Constants.regex_command).Groups[1].Value;
                    switch (command.ToLower())
                    {
                    case "create":
                        return(createCommand(message));

                    case "topfeatures":
                        return(logicAppCommand(message, "TopFeatures"));

                    case "topbugs":
                        return(logicAppCommand(message, "TopBugs"));

                    case "topcri":
                        return(logicAppCommand(message, "TopCRI"));

                    case "currentsprint":
                        return(logicAppCommand(message, "CurrentSprint"));

                    case "start":
                        return(message.CreateReplyMessage("Please welcome your bot overlord", "en"));

                    case "logout":
                        var getData = await client.Bots.GetUserDataAsync(Constants.botId, message.From.Id);

                        getData.Data = null;
                        await client.Bots.SetUserDataAsync(Constants.botId, message.From.Id, getData);

                        return(message.CreateReplyMessage("You have been logged out"));

                    default:
                        return(message.CreateReplyMessage("Sorry, that's an invalid command", "en"));
                    }
                }
                #endregion
                else
                {
                    var reply = await Conversation.SendAsync(message, () => new VSTFDialog());

                    #region Check if I need to go start up a query or create
                    var dialogQuery  = reply.GetBotConversationData <QueryItem>("userQuery");
                    var dialogCreate = reply.GetBotConversationData <TFSItem>("userItem");
                    if (dialogQuery != null)
                    {
                        reply.SetBotConversationData("userQuery", null);
                        Task.Factory.StartNew(async() =>
                        {
                            await getQueryResults(message, dialogQuery);
                        });
                    }
                    else if (dialogCreate != null)
                    {
                        reply.SetBotConversationData("userItem", null);
                        Task.Factory.StartNew(() =>
                        {
                            createTFSItem(message, dialogCreate);
                        });
                    }

                    #endregion

                    return(reply);
                }
            }
            else
            {
                return(HandleSystemMessage(message));
            }
        }
예제 #6
0
        public static async Task <AuthenticationResult> GetTokenByTenant(string tenantId)
        {
            bool found       = false;
            var  tenantCache = TenantCache.GetCache();

            if (tenantCache.ContainsKey(tenantId))
            {
                found = true;
            }

            if (!found)
            {
                foreach (var tenant in tenantCache)
                {
                    if (tenant.Value.subscriptions.Any(s => s.subscriptionId == tenantId))
                    {
                        tenantId = tenant.Key;
                        found    = true;
                        break;
                    }
                }
            }

            if (!found)
            {
                throw new InvalidOperationException(String.Format("Cannot find tenant {0} in cache!", tenantId));
            }

            var tokenCache  = TokenCache.GetCache();
            var authResults = tokenCache.Where(p => p.Key.TenantId == tenantId)
                              .Select(p => AuthenticationResult.Deserialize(Encoding.UTF8.GetString(Convert.FromBase64String(p.Value)))).ToArray();

            if (authResults.Length <= 0)
            {
                throw new InvalidOperationException(String.Format("Cannot find tenant {0} in cache!", tenantId));
            }

            if (authResults.Length > 1)
            {
                foreach (var authResult in authResults)
                {
                    Console.WriteLine(authResult.UserInfo.UserId);
                }

                throw new InvalidOperationException("Multiple users found.  Please specify user argument!");
            }
            else
            {
                var authResult = authResults[0];
                if (authResult.ExpiresOn <= DateTime.UtcNow)
                {
                    authResult = await GetAuthorizationResult(tokenCache, authResult.TenantId, authResult.UserInfo.UserId);

                    TokenCache.SaveCache(tokenCache);
                }

                SaveRecentToken(authResult);

                return(authResult);
            }
        }