Exemple #1
0
        public async Task TokenTests_RefreshTestLoad()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("12604f0f-bc92-4318-a6dd-aed704445ba4", "H_k}}7b75BEl+KY1");
            List <Task <string> >   tasks       = new List <Task <string> >();

            for (int i = 0; i < 1000; i++)
            {
                tasks.Add(credentials.GetTokenAsync());
            }

            string prevResult = null;

            foreach (var item in tasks)
            {
                string result = await item;
                Assert.NotNull(result);
                if (prevResult != null)
                {
                    Assert.Equal(prevResult, result);
                }
                prevResult = result;
            }

            tasks.Clear();
            for (int i = 0; i < 1000; i++)
            {
                if (i % 100 == 50)
                {
                    tasks.Add(credentials.GetTokenAsync(true));
                }
                else
                {
                    tasks.Add(credentials.GetTokenAsync());
                }
            }

            HashSet <string> results = new HashSet <string>();

            for (int i = 0; i < 1000; i++)
            {
                string result = await tasks[i];
                if (i == 0)
                {
                    results.Add(result);
                }
                Assert.NotNull(result);
                if (prevResult != null)
                {
                    if (i % 100 == 50)
                    {
                        Assert.True(!results.Contains(result));
                        results.Add(result);
                    }
                    else
                    {
                        Assert.Contains(result, results);
                    }
                }
            }
        }
        public async Task TokenTests_RefreshTestLoad()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("a40e1db0-b7a2-4e6e-af0e-b4987f73228f", "sbF0902^}tyvpvEDXTMX9^|");

            List <Task <string> > tasks = new List <Task <string> >();

            for (int i = 0; i < 1000; i++)
            {
                tasks.Add(credentials.GetTokenAsync());
            }

            foreach (var item in tasks)
            {
                Assert.IsFalse(item.IsFaulted);
                Assert.IsFalse(item.IsCanceled);
                string result = await item;
            }

            tasks.Clear();
            bool forceRefresh = false;

            for (int i = 0; i < 1000; i++)
            {
                forceRefresh = i % 100 == 50;
                tasks.Add(credentials.GetTokenAsync(forceRefresh));
            }

            for (int i = 0; i < 1000; i++)
            {
                Assert.IsFalse(tasks[i].IsFaulted);
                Assert.IsFalse(tasks[i].IsCanceled);
                string result = await tasks[i];
            }
        }
Exemple #3
0
        public async Task TokenTests_RefreshTestLoad()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("10c55330-7945-4008-b2c5-9e91cb5e5d34", "cPVCp1|l!8T=>-Fz");
            List <Task <string> >   tasks       = new List <Task <string> >();

            for (int i = 0; i < 1000; i++)
            {
                tasks.Add(credentials.GetTokenAsync());
            }

            string prevResult = null;

            foreach (var item in tasks)
            {
                string result = await item;
                Assert.NotNull(result);
                if (prevResult != null)
                {
                    Assert.Equal(prevResult, result);
                }
                prevResult = result;
            }

            tasks.Clear();
            for (int i = 0; i < 1000; i++)
            {
                if (i % 100 == 50)
                {
                    tasks.Add(credentials.GetTokenAsync(true));
                }
                else
                {
                    tasks.Add(credentials.GetTokenAsync());
                }
            }

            HashSet <string> results = new HashSet <string>();

            for (int i = 0; i < 1000; i++)
            {
                string result = await tasks[i];
                if (i == 0)
                {
                    results.Add(result);
                }
                Assert.NotNull(result);
                if (prevResult != null)
                {
                    if (i % 100 == 50)
                    {
                        Assert.True(!results.Contains(result));
                        results.Add(result);
                    }
                    else
                    {
                        Assert.Contains(result, results);
                    }
                }
            }
        }
        public async Task TokenTests_GetTokenTwice()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("a40e1db0-b7a2-4e6e-af0e-b4987f73228f", "sbF0902^}tyvpvEDXTMX9^|");
            var result = await credentials.GetTokenAsync();

            Assert.IsNotNull(result);
            var result2 = await credentials.GetTokenAsync();

            Assert.AreEqual(result2, result2);
        }
Exemple #5
0
        public async Task TokenTests_GetTokenWaitAndRefresh()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("a40e1db0-b7a2-4e6e-af0e-b4987f73228f", "sbF0902^}tyvpvEDXTMX9^|");
            var result = await credentials.GetTokenAsync();

            Assert.IsNotNull(result);
            credentials.ClearTokenCache();
            var result2 = await credentials.GetTokenAsync();

            Assert.AreNotEqual(result.ExpiresOn, result2.ExpiresOn);
            Assert.AreNotEqual(result.AccessToken, result2.AccessToken);
        }
Exemple #6
0
        public async Task TokenTests_RefreshTokenWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("10c55330-7945-4008-b2c5-9e91cb5e5d34", "cPVCp1|l!8T=>-Fz");
            var result = await credentials.GetTokenAsync();

            Assert.IsNotNull(result);
            var result2 = await credentials.GetTokenAsync();

            Assert.AreEqual(result, result2);
            var result3 = await credentials.GetTokenAsync(true);

            Assert.AreNotEqual(result2, result3);
        }
Exemple #7
0
        public async Task TokenTests_RefreshTokenWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(testAppId, testPassword);
            var result = await credentials.GetTokenAsync();

            Assert.IsNotNull(result);
            var result2 = await credentials.GetTokenAsync();

            Assert.AreEqual(result, result2);
            var result3 = await credentials.GetTokenAsync(true);

            Assert.IsNotNull(result3);
            Assert.IsNotNull(result2, result3);
        }
Exemple #8
0
        //[Fact]
        public async Task TokenTests_RefreshTokenWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("12604f0f-bc92-4318-a6dd-aed704445ba4", "H_k}}7b75BEl+KY1");
            var result = await credentials.GetTokenAsync();

            Assert.NotNull(result);
            var result2 = await credentials.GetTokenAsync();

            Assert.Equal(result, result2);
            var result3 = await credentials.GetTokenAsync(true);

            Assert.NotNull(result3);
            Assert.NotEqual(result2, result3);
        }
Exemple #9
0
        public async Task TokenTests_GetCredentialsWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(testAppId, testPassword);
            var result = await credentials.GetTokenAsync();

            Assert.IsNotNull(result);
        }
Exemple #10
0
        public async Task TokenTests_GetCredentialsWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("10c55330-7945-4008-b2c5-9e91cb5e5d34", "cPVCp1|l!8T=>-Fz");
            var result = await credentials.GetTokenAsync();

            Assert.NotNull(result);
        }
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            var appID       = ConfigurationManager.AppSettings["MicrosoftAppId"];
            var appPassword = ConfigurationManager.AppSettings["MicrosoftAppPassword"];

            //Trace.WriteLine("Application Started");

            if (!string.IsNullOrEmpty(appID) && !string.IsNullOrEmpty(appPassword))
            {
                var credentials = new MicrosoftAppCredentials(appID, appPassword);

                Task.Factory.StartNew(async() =>
                {
                    while (!_getTokenAsyncCancellation.IsCancellationRequested)
                    {
                        try
                        {
                            var token = await credentials.GetTokenAsync().ConfigureAwait(false);
                        }
                        catch (MicrosoftAppCredentials.OAuthException ex)
                        {
                            Trace.TraceError(ex.Message);
                        }
                        await Task.Delay(TimeSpan.FromMinutes(30), _getTokenAsyncCancellation.Token).ConfigureAwait(false);
                    }
                }).ConfigureAwait(false);
            }
        }
Exemple #12
0
        //[Fact]
        public async Task TokenTests_GetCredentialsFromTenantWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("645cd89f-a83e-4af9-abb5-a454e917cbc4", "jvoMWRBA67:zjgePZ359_-_", "microsoft.com", null);
            var result = await credentials.GetTokenAsync();

            Assert.NotNull(result);
        }
Exemple #13
0
        public async Task TokenTests_GetCredentialsWorks()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("12604f0f-bc92-4318-a6dd-aed704445ba4", "H_k}}7b75BEl+KY1");
            var result = await credentials.GetTokenAsync();

            Assert.NotNull(result);
        }
Exemple #14
0
        public BotJwtRefreshWorker()
        {
            var appID       = System.Configuration.ConfigurationManager.AppSettings["MicrosoftAppId"];
            var appPassword = System.Configuration.ConfigurationManager.AppSettings["MicrosoftAppPassword"];

            if (!string.IsNullOrEmpty(appID) && !string.IsNullOrEmpty(appPassword))
            {
                var credentials = new MicrosoftAppCredentials(appID, appPassword);
                Task.Factory.StartNew(
                    async() =>
                {
                    var ct = _Cts.Token;
                    while (!ct.IsCancellationRequested)
                    {
                        try
                        {
                            // GetTokenAsync method internally calls RefreshAndStoreToken,
                            // meaning that the token will automatically be cached at this point
                            // and you don’t need to do anything else – the bot will always have a valid token.
                            await credentials.GetTokenAsync().ConfigureAwait(false);
                            WebApiConfig.TelemetryClient.TrackEvent("BotJwtRefreshWorker.TokenRefreshed");
                        }
                        catch (Exception ex)
                        {
                            WebApiConfig.TelemetryClient.TrackException(ex, new Dictionary <string, string>
                            {
                                { "class", "BotJwtRefreshWorker" }
                            });
                        }
                        await Task.Delay(TimeSpan.FromMinutes(30), ct).ConfigureAwait(false);
                    }
                },
                    TaskCreationOptions.LongRunning);
            }
        }
 public BotJwtRefreshWorker()
 {
     var appID = ServiceHelper.AppId;
     var appPassword = ServiceHelper.AppSecret;
     if (!string.IsNullOrEmpty(appID) && !string.IsNullOrEmpty(appPassword))
     {
         var credentials = new MicrosoftAppCredentials(appID, appPassword);
         Task.Factory.StartNew(
             async () =>
             {
                 var ct = _Cts.Token;
                 while (!ct.IsCancellationRequested)
                 {
                     try
                     {
                     // GetTokenAsync method internally calls RefreshAndStoreToken, meaning that the token will automatically be cached at this point and you don’t need to do anything else – the bot will always have a valid token.
                     await credentials.GetTokenAsync().ConfigureAwait(false);
                     }
                     catch (Exception ex)
                     {
                         Trace.TraceError(ex.ToString());
                     }
                     await Task.Delay(TimeSpan.FromMinutes(30), ct).ConfigureAwait(false);
                 }
             },
              TaskCreationOptions.LongRunning);
     }
 }
Exemple #16
0
        public BaseTest()
        {
            if (mode == HttpRecorderMode.Record || mode == HttpRecorderMode.None)
            {
                var credentials = new MicrosoftAppCredentials(ClientId, ClientSecret);
                var task        = credentials.GetTokenAsync();
                task.Wait();
                this.token = task.Result;

                // Helpful for generating recordings when debugging locally
                Environment.SetEnvironmentVariable("AZURE_TEST_MODE", mode.ToString());
            }
            else
            {
                this.token = "STUB_TOKEN";
            }

            Bot = new ChannelAccount()
            {
                Id = BotId
            };
            User = new ChannelAccount()
            {
                Id = UserId
            };
        }
Exemple #17
0
        public async Task TokenTests_RefreshTestLoad()
        {
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials("a40e1db0-b7a2-4e6e-af0e-b4987f73228f", "sbF0902^}tyvpvEDXTMX9^|");

            List <Task <AuthenticationResult> > tasks = new List <Task <AuthenticationResult> >();

            for (int i = 0; i < 1000; i++)
            {
                tasks.Add(credentials.GetTokenAsync());
            }

            foreach (var item in tasks)
            {
                Assert.IsFalse(item.IsFaulted);
                Assert.IsFalse(item.IsCanceled);
                AuthenticationResult result = await item;

                Assert.IsTrue(result.ExpiresOn > DateTimeOffset.UtcNow);
            }

            tasks.Clear();
            for (int i = 0; i < 1000; i++)
            {
                if (i % 100 == 50)
                {
                    credentials.ClearTokenCache();
                }

                tasks.Add(credentials.GetTokenAsync());
            }

            HashSet <AuthenticationResult> results = new HashSet <AuthenticationResult>(new AuthenticationResultEqualityComparer());

            for (int i = 0; i < 1000; i++)
            {
                Assert.IsFalse(tasks[i].IsFaulted);
                Assert.IsFalse(tasks[i].IsCanceled);
                AuthenticationResult result = await tasks[i];

                Assert.IsTrue(result.ExpiresOn > DateTimeOffset.UtcNow);
            }
        }
        public static async Task <ConnectorClient> BuildConnectorClientAsync(string serviceUrl)
        {
            var account = new MicrosoftAppCredentials(
                ConfigurationManager.AppSettings["MicrosoftAppId"],
                ConfigurationManager.AppSettings["MicrosoftAppPassword"]);

            Trace.TraceInformation($"MicrosoftAppId is {ConfigurationManager.AppSettings["MicrosoftAppId"]} and " +
                                   $"MicrosoftAppPassword is {ConfigurationManager.AppSettings["MicrosoftAppPassword"]}");
            var jwtToken = await account.GetTokenAsync();

            return(new ConnectorClient(new Uri(serviceUrl), ConfigurationManager.AppSettings["MicrosoftAppId"],
                                       ConfigurationManager.AppSettings["MicrosoftAppPassword"], handlers: new AddAuthorizationHeaderHandler(jwtToken)));
        }
        /// <summary>
        /// Gets the content of the inline image attachment.
        /// </summary>
        /// <param name="contentUrl">The URL to the image.</param>
        /// <param name="appCredentials">The credentials to use when downloading the image.</param>
        /// <param name="httpClient">The client to use when downloading the image.</param>
        /// <returns>The image contents</returns>
        public static async Task <byte[]> GetInlineAttachmentContentAsync(string contentUrl, MicrosoftAppCredentials appCredentials, HttpClient httpClient = null)
        {
            httpClient = httpClient ?? new HttpClient();

            var request = new HttpRequestMessage(HttpMethod.Get, contentUrl);

            var token = await appCredentials.GetTokenAsync();

            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var response = await httpClient.SendAsync(request);

            response.EnsureSuccessStatusCode();

            var data = await response.Content.ReadAsByteArrayAsync();

            return(data);
        }
        public async Task <IActionResult> SendSkypeMessage()
        {
            var activity = _dialogsRepository.GetAllDialogs().LastOrDefault();

            var endpointService = _botConfiguration.Services.FirstOrDefault(x => typeof(EndpointService).Equals(x.GetType()) && x.Name.Equals("production")) as EndpointService;

            var account = new MicrosoftAppCredentials(endpointService.AppId, endpointService.AppPassword);
            var token   = await account.GetTokenAsync();

            MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl, DateTime.Now.AddDays(7));

            var userAccount = new ChannelAccount(activity.From.Id, activity.From.Name);
            var botAccount  = new ChannelAccount(activity.Recipient.Id, activity.Recipient.Name);
            var connector   = new ConnectorClient(new Uri(activity.ServiceUrl), account, handlers: new TokenHandler(token));

            // Create a new message.
            IMessageActivity message        = Activity.CreateMessageActivity();
            string           conversationId = null;

            if (!string.IsNullOrEmpty(activity.Conversation.Id) && !string.IsNullOrEmpty(activity.ChannelId))
            {
                // If conversation ID and channel ID was stored previously, use it.
                message.ChannelId = activity.ChannelId;
            }
            else
            {
                // Conversation ID was not stored previously, so create a conversation.
                // Note: If the user has an existing conversation in a channel, this will likely create a new conversation window.
                conversationId = (await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount)).Id;
            }

            // Set the address-related properties in the message and send the message.
            message.From         = botAccount;
            message.Recipient    = userAccount;
            message.Conversation = new ConversationAccount(id: conversationId ?? activity.Conversation.Id);
            message.Text         = "COMMIT";
            message.Locale       = "en-us";
            await connector.Conversations.SendToConversationAsync((Activity)message);

            return(Ok());
        }
Exemple #21
0
#pragma warning disable 162

        public BaseTest()
        {
            if (mode == HttpRecorderMode.Record)
            {
                var credentials = new MicrosoftAppCredentials(clientId, clientSecret);
                var task        = credentials.GetTokenAsync();
                task.Wait();
                this.token = task.Result;
            }
            else
            {
                this.token = "STUB_TOKEN";
            }

            Bot = new ChannelAccount()
            {
                Id = botId
            };
            User = new ChannelAccount()
            {
                Id = userId
            };
        }
Exemple #22
0
        public async Task TokenTests_RefreshTestLoad()
        {
            EnsureSettings();
            MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(testAppId, testPassword);
            List <Task <string> >   tasks       = new List <Task <string> >();

            for (int i = 0; i < 1000; i++)
            {
                tasks.Add(credentials.GetTokenAsync());
            }

            string prevResult = null;

            foreach (var item in tasks)
            {
                string result = await item;
                Assert.IsNotNull(result);
                if (prevResult != null)
                {
                    Assert.AreEqual(prevResult, result);
                }

                prevResult = result;
            }

            tasks.Clear();
            for (int i = 0; i < 1000; i++)
            {
                if (i % 100 == 50)
                {
                    tasks.Add(credentials.GetTokenAsync(true));
                }
                else
                {
                    tasks.Add(credentials.GetTokenAsync());
                }
            }

            HashSet <string> results = new HashSet <string>();

            for (int i = 0; i < 1000; i++)
            {
                string result = await tasks[i];
                if (i == 0)
                {
                    results.Add(result);
                    Assert.IsNotNull(result);
                }

                if (prevResult != null)
                {
                    if (i % 100 == 50)
                    {
                        Assert.IsTrue(!results.Contains(result));
                        results.Add(result);
                    }
                    else
                    {
                        // Xunit.Assert.Contains(result, results);
                        Assert.IsTrue(results.Contains(result));
                    }
                }
            }
        }
Exemple #23
0
    public async Task <HttpOperationResponse <object> > SendToConversationWithHttpMessagesAsync(Activity activity,
                                                                                                string conversationId, Dictionary <string, List <string> > customHeaders = null,
                                                                                                CancellationToken cancellationToken = default(CancellationToken))
    {
        if (activity == null)
        {
            throw new ValidationException(ValidationRules.CannotBeNull, "activity");
        }
        if (conversationId == null)
        {
            throw new ValidationException(ValidationRules.CannotBeNull, "conversationId");
        }
        // Construct URL
        var baseUrl = Client.BaseUri.AbsoluteUri;
        var url     = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")),
                              "v3/conversations/{conversationId}/activities").ToString();

        url = url.Replace("{conversationId}", Uri.EscapeDataString(conversationId));
        // Create HTTP transport objects
        var httpRequest = new HttpRequestMessage
        {
            Method     = new HttpMethod("POST"),
            RequestUri = new Uri(url)
        };
        var cred  = new MicrosoftAppCredentials("{Your bot id}", "{Your bot pwd}");
        var token = await cred.GetTokenAsync();

        httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        // Set Headers
        if (customHeaders != null)
        {
            foreach (var header in customHeaders)
            {
                if (httpRequest.Headers.Contains(header.Key))
                {
                    httpRequest.Headers.Remove(header.Key);
                }
                httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }
        }
        // Serialize Request
        var requestContent = SafeJsonConvert.SerializeObject(activity, Client.SerializationSettings);

        httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
        httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
        // Set Credentials
        if (Client.Credentials != null)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
        }
        // Send Request
        cancellationToken.ThrowIfCancellationRequested();
        var httpResponse = await Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

        var statusCode = httpResponse.StatusCode;

        cancellationToken.ThrowIfCancellationRequested();
        string responseContent;

        if ((int)statusCode != 200 && (int)statusCode != 201 && (int)statusCode != 202 &&
            (int)statusCode != 400 && (int)statusCode != 401 && (int)statusCode != 403 &&
            (int)statusCode != 404 && (int)statusCode != 500 && (int)statusCode != 503)
        {
            var ex = new HttpOperationException(
                $"Operation returned an invalid status code '{statusCode}'");
            responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            ex.Request  = new HttpRequestMessageWrapper(httpRequest, requestContent);
            ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
            httpRequest.Dispose();
            httpResponse.Dispose();
            throw ex;
        }
        // Create Result
        var result = new HttpOperationResponse <object>
        {
            Request  = httpRequest,
            Response = httpResponse
        };

        responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

        try
        {
            result.Body =
                SafeJsonConvert.DeserializeObject <ResourceResponse>(responseContent,
                                                                     Client.DeserializationSettings);
        }
        catch (JsonException ex)
        {
            httpRequest.Dispose();
            httpResponse.Dispose();
            throw new SerializationException("Unable to deserialize the response.", responseContent, ex);
        }
        return(result);
    }