Exemplo n.º 1
0
        //吳家寶
        private async Task <ConversationResourceResponse> NewConversationAsync(string teamsChannelId, Attachment card)
        {
            //teamsChannelId: Teams channel id in which to create the post.

            //The Bot Service Url needs to be dynamically fetched (and stored) from the Team. Recommendation is to capture the serviceUrl from the bot Payload and later re-use it to send proactive messages.
            string serviceUrl = "https://smba.trafficmanager.net/emea/";
            //From the Bot Channel Registration

            string botClientID     = "81459ba9-bf90-4527-bad4-b8cace1c47f3";
            string botClientSecret = "td-Yft_qf-~OIucKnMEB_fb-2k.xS89Wc4";

            AppCredentials.TrustServiceUrl(serviceUrl);
            var connectorClient         = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
            var topLevelMessageActivity = MessageFactory.Attachment(card);

            var conversationParameters = new ConversationParameters
            {
                IsGroup     = true,
                ChannelData = new TeamsChannelData
                {
                    Channel = new ChannelInfo(teamsChannelId),
                },
                Activity = (Activity)topLevelMessageActivity
            };

            return(await connectorClient.Conversations.CreateConversationAsync(conversationParameters));

            // await connectorClient.Conversations.CreateConversationAsync(conversationParameters);
        }
Exemplo n.º 2
0
        private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            AppCredentials.TrustServiceUrl(turnContext.Activity.ServiceUrl);

            // If you encounter permission-related errors when sending this message, see
            // https://aka.ms/BotTrustServiceUrl
            await turnContext.SendActivityAsync("proactive hello");
        }
        private async Task SendMessageAsync(string message, NotificationDetails notification)
        {
            var activity = MessageFactory.Text(message);

            activity.Summary = message;
            activity.TeamsNotifyUser();

            AppCredentials.TrustServiceUrl(ServiceUrl);

            var credentials = new MicrosoftAppCredentials(appId, appPassword);

            var connectorClient = new ConnectorClient(new Uri(ServiceUrl), credentials);
            await connectorClient.Conversations.SendToConversationAsync(notification.ChannelId, activity);
        }
Exemplo n.º 4
0
        private async void UpdateCardInTeams(BlobDataDeserializer blobData, Attachment adaptiveCardAttachment)
        {
            using var connector = new ConnectorClient(new Uri(Constants.ServiceUrl), Constants.MicrosoftAppId, Constants.MicrosoftAppPassword);
            AppCredentials.TrustServiceUrl(Constants.ServiceUrl, DateTime.MaxValue);
            var updateActivity = new Activity();

            updateActivity.Id          = blobData.messageId;
            updateActivity.Type        = "message";
            updateActivity.Attachments = new List <Attachment> {
                adaptiveCardAttachment
            };
            updateActivity.Conversation = new ConversationAccount(id: blobData.conversationId);
            await connector.Conversations.UpdateActivityAsync(updateActivity);
        }
        /// <summary>
        /// Validates the auth header for WebSocket upgrade requests.
        /// </summary>
        /// <remarks>
        /// Returns a ClaimsIdentity for successful auth and when auth is disabled. Returns null for failed auth.
        /// </remarks>
        /// <param name="httpRequest">The connection request.</param>
        private async Task <ClaimsIdentity> AuthenticateRequestAsync(HttpRequest httpRequest)
        {
            try
            {
                if (!await CredentialProvider.IsAuthenticationDisabledAsync().ConfigureAwait(false))
                {
                    var authHeader = httpRequest.Headers.First(x => string.Equals(x.Key, AuthHeaderName, StringComparison.OrdinalIgnoreCase)).Value.FirstOrDefault();
                    var channelId  = httpRequest.Headers.First(x => string.Equals(x.Key, ChannelIdHeaderName, StringComparison.OrdinalIgnoreCase)).Value.FirstOrDefault();

                    if (string.IsNullOrWhiteSpace(authHeader))
                    {
                        await WriteUnauthorizedResponseAsync(AuthHeaderName, httpRequest).ConfigureAwait(false);

                        return(null);
                    }

                    if (string.IsNullOrWhiteSpace(channelId))
                    {
                        await WriteUnauthorizedResponseAsync(ChannelIdHeaderName, httpRequest).ConfigureAwait(false);

                        return(null);
                    }

                    var claimsIdentity = await JwtTokenValidation.ValidateAuthHeader(authHeader, CredentialProvider, ChannelProvider, channelId).ConfigureAwait(false);

                    if (!claimsIdentity.IsAuthenticated)
                    {
                        httpRequest.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        return(null);
                    }

                    // Add ServiceURL to the cache of trusted sites in order to allow token refreshing.
                    AppCredentials.TrustServiceUrl(claimsIdentity.FindFirst(AuthenticationConstants.ServiceUrlClaim).Value);
                    ClaimsIdentity = claimsIdentity;
                    return(claimsIdentity);
                }

                // Authentication is not enabled, therefore return an anonymous ClaimsIdentity.
                return(new ClaimsIdentity(new List <Claim>(), "anonymous"));
            }
            catch (Exception)
            {
                httpRequest.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                await httpRequest.HttpContext.Response.WriteAsync("Error while attempting to authorize connection.").ConfigureAwait(false);

                throw;
            }
        }
Exemplo n.º 6
0
        private async Task <bool> AuthenticateRequestAsync(HttpRequest httpRequest)
        {
            try
            {
                if (!await CredentialProvider.IsAuthenticationDisabledAsync().ConfigureAwait(false))
                {
                    var authHeader = httpRequest.Headers.First(x => x.Key.ToLower() == AuthHeaderName).Value.FirstOrDefault();
                    var channelId  = httpRequest.Headers.First(x => x.Key.ToLower() == ChannelIdHeaderName).Value.FirstOrDefault();

                    if (string.IsNullOrWhiteSpace(authHeader))
                    {
                        await WriteUnauthorizedResponseAsync(AuthHeaderName, httpRequest).ConfigureAwait(false);

                        return(false);
                    }

                    if (string.IsNullOrWhiteSpace(channelId))
                    {
                        await WriteUnauthorizedResponseAsync(ChannelIdHeaderName, httpRequest).ConfigureAwait(false);

                        return(false);
                    }

                    var claimsIdentity = await JwtTokenValidation.ValidateAuthHeader(authHeader, CredentialProvider, ChannelProvider, channelId).ConfigureAwait(false);

                    if (!claimsIdentity.IsAuthenticated)
                    {
                        httpRequest.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        return(false);
                    }

                    // Add ServiceURL to the cache of trusted sites in order to allow token refreshing.
                    AppCredentials.TrustServiceUrl(claimsIdentity.FindFirst(AuthenticationConstants.ServiceUrlClaim).Value);
                    ClaimsIdentity = claimsIdentity;
                }

                return(true);
            }
            catch (Exception ex)
            {
                httpRequest.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                await httpRequest.HttpContext.Response.WriteAsync("Error while attempting to authorize connection.").ConfigureAwait(false);

                throw ex;
            }
        }
Exemplo n.º 7
0
        private async Task <bool> AuthenticateRequestAsync(HttpRequestMessage httpRequest, HttpResponseMessage httpResponse)
        {
            try
            {
                if (!await CredentialProvider.IsAuthenticationDisabledAsync().ConfigureAwait(false))
                {
#pragma warning disable CA1308 // Normalize strings to uppercase (header names come in lowercase, ignoring)
                    var authHeader = httpRequest.Headers.GetValues(AuthHeaderName.ToLowerInvariant()).FirstOrDefault();
                    var channelId  = httpRequest.Headers.GetValues(ChannelIdHeaderName.ToLowerInvariant()).FirstOrDefault();
#pragma warning restore CA1308 // Normalize strings to uppercase

                    if (string.IsNullOrWhiteSpace(authHeader))
                    {
                        WriteUnauthorizedResponse(AuthHeaderName, httpResponse);
                        return(false);
                    }

                    if (string.IsNullOrWhiteSpace(channelId))
                    {
                        WriteUnauthorizedResponse(ChannelIdHeaderName, httpResponse);
                        return(false);
                    }

                    var claimsIdentity = await JwtTokenValidation.ValidateAuthHeader(authHeader, CredentialProvider, ChannelProvider, channelId).ConfigureAwait(false);

                    if (!claimsIdentity.IsAuthenticated)
                    {
                        httpResponse.StatusCode = HttpStatusCode.Unauthorized;
                        return(false);
                    }

                    // Add ServiceURL to the cache of trusted sites in order to allow token refreshing.
                    AppCredentials.TrustServiceUrl(claimsIdentity.FindFirst(AuthenticationConstants.ServiceUrlClaim).Value);
                    ClaimsIdentity = claimsIdentity;
                }

                return(true);
            }
            catch (Exception)
            {
                httpResponse.StatusCode = HttpStatusCode.InternalServerError;
                httpResponse.Content    = new StringContent("Error while attempting to authorize connection.");
                throw;
            }
        }
Exemplo n.º 8
0
        public GameStart(IConfiguration configuration, IAdaptiveTemplateLoader loader, Dictionary <string, string> convos)
        {
            _appId       = configuration["MicrosoftAppId"];
            _appPassword = configuration["MicrosoftAppPassword"];
            AppCredentials.TrustServiceUrl("https://smba.trafficmanager.net/amer/");
            this.client = new ConnectorClient(new Uri("https://smba.trafficmanager.net/amer/"), microsoftAppId: this._appId, microsoftAppPassword: this._appPassword);

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(this._appId)
                                                                           .WithTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47")
                                                                           .WithClientSecret(this._appPassword)
                                                                           .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            this.graphClient = new GraphServiceClient(authProvider);

            this.convos = convos;

            this.gameStartTemplate  = loader.InitializeAdaptiveTemplate("MatchStart.json");
            this.gameUpdateTemplate = loader.InitializeAdaptiveTemplate("MatchUpdate.json");
        }