public CredentialsCommand(AppCredentials appCreds)
 {
     this.Method         = "credentials";
     this.Data           = new Dictionary <string, string>();
     this.Data["id"]     = appCreds.id;
     this.Data["secret"] = appCreds.secret;
 }
        public RetrieveSecureAppCredentials()
        {
            var configs = GetConfiguration.GetConfigs;

            AppCredentials = configs.Configuration.GetSection("AppCredentials")
                             .Get <AppCredentials>();
        }
Beispiel #3
0
        public ToDoApiShould()
        {
            var credentials = new AppCredentials
            {
                AppId     = "5b9ed3b6-652c-4ba5-b6cd-5438dba1ac15",
                AppSecret = "U4byxd0fsqYjTopaem6a2YV"
            };

            // I need to create own `TestServer` because default `TestServer`
            // doesn't allow you to configure the client created by testserver.
            // For example adding other delegating handler
            _server = new CustomTestServer(new WebHostBuilder()
                                           .UseStartup <Startup>());

            // This creates test http client with RefreshTokenHandler,
            // so when you get `Unauthorized` the handler will try to get new access_token and refresh_token
            // and store them using `token store`

            _client = _server.CreateClient(TokenStore, credentials);

            _testEventModels = new List <EventModel>();
            _testTaskModels  = new List <TaskModel>();

            TestDataClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", TokenStore.AccessToken);
            CreateTestData().Wait();
        }
        //吳家寶
        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);
        }
Beispiel #5
0
        /// <summary>
        /// Creates the connector client asynchronous.
        /// </summary>
        /// <param name="serviceUrl">The service URL.</param>
        /// <param name="claimsIdentity">The claims identity.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>ConnectorClient instance.</returns>
        /// <exception cref="NotSupportedException">ClaimsIdentity cannot be null. Pass Anonymous ClaimsIdentity if authentication is turned off.</exception>
        private async Task <IConnectorClient> CreateConnectorClientAsync(string serviceUrl, ClaimsIdentity claimsIdentity, CancellationToken cancellationToken)
        {
            if (claimsIdentity == null)
            {
                throw new NotSupportedException("ClaimsIdentity cannot be null. Pass Anonymous ClaimsIdentity if authentication is turned off.");
            }

            // For requests from channel App Id is in Audience claim of JWT token. For emulator it is in AppId claim. For
            // unauthenticated requests we have anonymous identity provided auth is disabled.
            // For Activities coming from Emulator AppId claim contains the Bot's AAD AppId.
            var botAppIdClaim = claimsIdentity.Claims?.SingleOrDefault(claim => claim.Type == AuthenticationConstants.AudienceClaim);

            if (botAppIdClaim == null)
            {
                botAppIdClaim = claimsIdentity.Claims?.SingleOrDefault(claim => claim.Type == AuthenticationConstants.AppIdClaim);
            }

            // For anonymous requests (requests with no header) appId is not set in claims.
            AppCredentials appCredentials = null;

            if (botAppIdClaim != null)
            {
                var    botId = botAppIdClaim.Value;
                string scope = null;
                if (SkillValidation.IsSkillClaim(claimsIdentity.Claims))
                {
                    // The skill connector has the target skill in the OAuthScope.
                    scope = JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims);
                }

                appCredentials = await GetAppCredentialsAsync(botId, scope, cancellationToken).ConfigureAwait(false);
            }

            return(CreateConnectorClient(serviceUrl, appCredentials));
        }
Beispiel #6
0
        public PhoneSkillDialogBase(
            string dialogId,
            IServiceProvider serviceProvider)
            : base(dialogId)
        {
            Settings        = serviceProvider.GetService <BotSettings>();
            Services        = serviceProvider.GetService <BotServices>();
            TemplateManager = serviceProvider.GetService <LocaleTemplateManager>();

            var conversationState = serviceProvider.GetService <ConversationState>();

            PhoneStateAccessor  = conversationState.CreateProperty <PhoneSkillState>(nameof(PhoneSkillState));
            DialogStateAccessor = conversationState.CreateProperty <DialogState>(nameof(DialogState));

            ServiceManager = serviceProvider.GetService <IServiceManager>();

            if (!Settings.OAuthConnections.Any())
            {
                throw new Exception("You must configure an authentication connection in your bot file before using this component.");
            }

            AppCredentials oauthCredentials = null;

            if (Settings.OAuthCredentials != null &&
                !string.IsNullOrWhiteSpace(Settings.OAuthCredentials.MicrosoftAppId) &&
                !string.IsNullOrWhiteSpace(Settings.OAuthCredentials.MicrosoftAppPassword))
            {
                oauthCredentials = new MicrosoftAppCredentials(Settings.OAuthCredentials.MicrosoftAppId, Settings.OAuthCredentials.MicrosoftAppPassword);
            }

            AddDialog(new MultiProviderAuthDialog(Settings.OAuthConnections, null, oauthCredentials));
            AddDialog(new EventPrompt(DialogIds.SkillModeAuth, "tokens/response", TokenResponseValidator));
        }
Beispiel #7
0
        /// <summary>
        /// Creates the connector client.
        /// </summary>
        /// <param name="serviceUrl">The service URL.</param>
        /// <param name="appCredentials">The application credentials for the bot.</param>
        /// <returns>Connector client instance.</returns>
        private IConnectorClient CreateConnectorClient(string serviceUrl, AppCredentials appCredentials = null)
        {
            var clientKey = $"{serviceUrl}{appCredentials?.MicrosoftAppId ?? string.Empty}";

            return(_connectorClients.GetOrAdd(clientKey, (key) =>
            {
                ConnectorClient connectorClient;
                if (appCredentials != null)
                {
                    connectorClient = new ConnectorClient(new Uri(serviceUrl), appCredentials, customHttpClient: _httpClient);
                }
                else
                {
                    var emptyCredentials = _channelProvider != null && _channelProvider.IsGovernment() ? MicrosoftGovernmentAppCredentials.Empty : MicrosoftAppCredentials.Empty;
                    connectorClient = new ConnectorClient(new Uri(serviceUrl), emptyCredentials, customHttpClient: _httpClient);
                }

                if (_connectorClientRetryPolicy != null)
                {
                    connectorClient.SetRetryPolicy(_connectorClientRetryPolicy);
                }

                return connectorClient;
            }));
        }
        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");
        }
        public MultiProviderAuthDialog(
            List <OAuthConnection> authenticationConnections,
            List <OAuthPromptSettings> promptSettings = null,
            AppCredentials oauthCredentials           = null)
            : base(nameof(MultiProviderAuthDialog))
        {
            _authenticationConnections = authenticationConnections ?? throw new ArgumentNullException(nameof(authenticationConnections));
            _oauthCredentials          = oauthCredentials;
            _responseManager           = new ResponseManager(
                AcceptedLocales,
                new AuthenticationResponses());

            var firstStep = new WaterfallStep[]
            {
                FirstStepAsync,
            };

            var authSteps = new WaterfallStep[]
            {
                PromptForProviderAsync,
                PromptForAuthAsync,
                HandleTokenResponseAsync,
            };

            AddDialog(new WaterfallDialog(DialogIds.FirstStepPrompt, firstStep));

            if (_authenticationConnections != null &&
                _authenticationConnections.Count > 0 &&
                _authenticationConnections.Any(c => !string.IsNullOrWhiteSpace(c.Name)))
            {
                for (int i = 0; i < _authenticationConnections.Count; ++i)
                {
                    var connection = _authenticationConnections[i];

                    foreach (var locale in AcceptedLocales)
                    {
                        // We ignore placeholder connections in config that don't have a Name
                        if (!string.IsNullOrWhiteSpace(connection.Name))
                        {
                            AddDialog(GetLocalizedDialog(locale, connection.Name, promptSettings?[i]));
                        }
                    }
                }

                AddDialog(new WaterfallDialog(DialogIds.AuthPrompt, authSteps));
                AddDialog(new ChoicePrompt(DialogIds.ProviderPrompt));
            }
            else
            {
                throw new ArgumentNullException(nameof(authenticationConnections));
            }
        }
Beispiel #10
0
        public async void Channel_MsaHeader_Valid_ServiceUrlShouldBeTrusted()
        {
            string header      = $"Bearer {await new MicrosoftAppCredentials("2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F").GetTokenAsync()}";
            var    credentials = new SimpleCredentialProvider("2cd87869-38a0-4182-9251-d056e8f0ac24", string.Empty);

            await JwtTokenValidation.AuthenticateRequest(
                new Activity { ServiceUrl = "https://smba.trafficmanager.net/amer-client-ss.msg/" },
                header,
                credentials,
                new SimpleChannelProvider(),
                emptyClient);

            Assert.True(AppCredentials.IsTrustedServiceUrl("https://smba.trafficmanager.net/amer-client-ss.msg/"));
        }
Beispiel #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MeetingService"/> class.
 /// </summary>
 /// <param name="httpClientFactory">The Http client factory.</param>
 /// <param name="botCredentials">The Bot credentials.</param>
 /// <param name="botAdapter">The Bot Framework HTTP adapter.</param>
 /// <param name="tenantInfoRepository">The TenantInfo repository.</param>
 /// <param name="meetingServiceOptions">App options related to the meetings service.</param>
 public MeetingService(
     IHttpClientFactory httpClientFactory,
     AppCredentials botCredentials,
     IBotFrameworkHttpAdapter botAdapter,
     ITenantInfoRepository tenantInfoRepository,
     IOptions <MeetingServiceOptions> meetingServiceOptions)
 {
     this.botCredentials       = botCredentials;
     this.botAdapter           = (BotFrameworkHttpAdapter)botAdapter;
     this.httpClient           = httpClientFactory.CreateClient();
     this.tenantInfoRepository = tenantInfoRepository;
     this.teamsAppId           = meetingServiceOptions.Value.TeamsAppId;
     this.contentBubbleUrl     = meetingServiceOptions.Value.ContentBubbleUrl;
 }
        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);
        }
        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);
        }
        public JsonResponseClient(IWebRequestCreator webRequestCreator, IWebRequestInvoker webRequestInvoker)
        {
            _appCredentials = new AppCredentials();

            _customHeaders = new NameValueCollection();
            if (_appCredentials.ApplicationKey != null)
            {
                SetAppKeyHeader(_appCredentials.ApplicationKey);
            }

            _argumentsAdder    = new ArgumentsAdder <T>();
            _urlSuffixGetter   = new UrlSuffixGetter <T>();
            _webRequestCreator = webRequestCreator;
            _webRequestInvoker = webRequestInvoker;
        }
        /// <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;
            }
        }
Beispiel #16
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;
            }
        }
Beispiel #17
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;
            }
        }
Beispiel #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "WebApp", Version = "v1"
                });
            });

            services.AddHttpClient();

            services.AddMindSphereSdkService(options =>
            {
                options.Credentials = AppCredentials.FromJsonFile(@"..\..\mdspcreds.json");
            });
        }
Beispiel #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotFrameworkSkillHostAdapter"/> class,
        /// using a credential provider.
        /// </summary>
        /// <param name="adapter">adapter that this skillAdapter is bound to.</param>
        /// <param name="credentials">The credentials to be used for token acquisition.</param>
        /// <param name="authConfig">The authentication configuration.</param>
        /// <param name="channelProvider">The channel provider.</param>
        /// <param name="connectorClientRetryPolicy">Retry policy for retrying HTTP operations.</param>
        /// <param name="customHttpClient">The HTTP client.</param>
        /// <param name="logger">The ILogger implementation this adapter should use.</param>
        /// <exception cref="ArgumentNullException">throw ArgumentNullException.</exception>
        /// <remarks>Use a <see cref="MiddlewareSet"/> object to add multiple middleware
        /// components in the constructor. Use the Use(<see cref="IMiddleware"/>) method to
        /// add additional middleware to the adapter after construction.
        /// </remarks>
        public BotFrameworkSkillHostAdapter(
            BotAdapter adapter,
            AppCredentials credentials,
            AuthenticationConfiguration authConfig,
            IChannelProvider channelProvider       = null,
            RetryPolicy connectorClientRetryPolicy = null,
            HttpClient customHttpClient            = null,
            ILogger logger = null)
            : base(adapter, logger)
        {
            _appCredentials             = credentials ?? throw new ArgumentNullException(nameof(credentials));
            _channelProvider            = channelProvider;
            _httpClient                 = customHttpClient ?? _defaultHttpClient;
            _connectorClientRetryPolicy = connectorClientRetryPolicy;
            _logger            = logger ?? NullLogger.Instance;
            _authConfiguration = authConfig ?? throw new ArgumentNullException(nameof(authConfig));

            // DefaultRequestHeaders are not thread safe so set them up here because this adapter should be a singleton.
            ConnectorClient.AddDefaultRequestHeaders(_httpClient);
        }
Beispiel #20
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");
        }
        static async Task Main(string[] args)
        {
            AppCredentials appCredentials = AppCredentials.FromJsonFile(@"..\..\..\..\..\mdspcreds.json");
            HttpClient     httpClient     = new HttpClient();

            AssetManagementClient assetClient = new AssetManagementClient(appCredentials, httpClient);


            ListAssetsRequest request = new ListAssetsRequest()
            {
                Size = 200
            };
            List <Asset> test = (await assetClient.ListAssetsAsync(request)).ToList();

            foreach (var item in test)
            {
                Console.WriteLine(item.AssetId);
            }

            Console.ReadKey();
        }
Beispiel #22
0
        public ToDoSkillDialogBase(
            string dialogId,
            IServiceProvider serviceProvider,
            IHttpContextAccessor httpContext)
            : base(dialogId)
        {
            _httpContext = httpContext;

            Settings        = serviceProvider.GetService <BotSettings>();
            Services        = serviceProvider.GetService <BotServices>();
            TemplateManager = serviceProvider.GetService <LocaleTemplateManager>();

            // Initialize state accessor
            var conversationState = serviceProvider.GetService <ConversationState>();

            ToDoStateAccessor = conversationState.CreateProperty <ToDoSkillState>(nameof(ToDoSkillState));

            var userState = serviceProvider.GetService <UserState>();

            UserStateAccessor = userState.CreateProperty <ToDoSkillUserState>(nameof(ToDoSkillUserState));

            ServiceManager = serviceProvider.GetService <IServiceManager>();

            AppCredentials oauthCredentials = null;

            if (Settings.OAuthCredentials != null &&
                !string.IsNullOrWhiteSpace(Settings.OAuthCredentials.MicrosoftAppId) &&
                !string.IsNullOrWhiteSpace(Settings.OAuthCredentials.MicrosoftAppPassword))
            {
                oauthCredentials = new MicrosoftAppCredentials(Settings.OAuthCredentials.MicrosoftAppId, Settings.OAuthCredentials.MicrosoftAppPassword);
            }

            AddDialog(new MultiProviderAuthDialog(Settings.OAuthConnections, null, oauthCredentials));
            AddDialog(new TextPrompt(Actions.Prompt));
            AddDialog(new ConfirmPrompt(Actions.ConfirmPrompt, null, Culture.English)
            {
                Style = ListStyle.SuggestedAction
            });
        }
Beispiel #23
0
        public async Task <Activity> GetDayActivityAsync(string Currentdate, string userId)
        {
            var appCredentials = AppCredentials.ToString();


            var oAuth_params = OAuthUtility.BuildBasicParameters(AppCredentials.ConsumerKey, AppCredentials.ConsumerSecret, "https://wbsapi.withings.net", HttpMethod.Get, this.AccessToken)
                               .Where(p => p.Key != "oauth_signature")
                               .OrderBy(p => p.Key);

            string startdate = ("2017-02-30");
            string date      = ("2017-03-24");

            string requestUri = $"https://wbsapi.withings.net/v2/measure?action=getactivity&userid={userId}&date={date}&";

            requestUri += string.Join("&", oAuth_params.Select(kvp => kvp.Key + "=" + kvp.Value));

            var signature = OAuthUtility.BuildBasicParameters(AppCredentials.ConsumerKey, AppCredentials.ConsumerSecret, requestUri, HttpMethod.Get, this.AccessToken)
                            .First((KeyValuePair <string, string> p) => p.Key == "oauth_signature").Value;

            string json = await HttpClient.GetStringAsync(requestUri + "&oauth_signature=" + signature);

            var o = JObject.Parse(json);


            return(new Activity
            {
                Calories = (float)o["body"]["calories"],
                Date = (string)o["body"]["date"],
                Distance = (float)o["body"]["distance"],
                Elevation = (float)o["body"]["elevation"],
                Intense = (int)o["body"]["intense"],
                Moderate = (int)o["body"]["moderate"],
                Soft = (int)o["body"]["soft"],
                Steps = (int)o["body"]["steps"],
                TimeZone = (string)o["body"]["timezone"],
                TotalCalories = (float)o["body"]["totalcalories"]
            });
        }
Beispiel #24
0
        public async Task <IEnumerable <MeasureGroup> > GetBodyMeasureAsync(string userId, string deviceType)
        {
            var appCredentials = AppCredentials.ToString();


            var oAuth_params = OAuthUtility.BuildBasicParameters(AppCredentials.ConsumerKey, AppCredentials.ConsumerSecret, "https://wbsapi.withings.net", HttpMethod.Get, this.AccessToken)
                               .Where(p => p.Key != "oauth_signature")
                               .OrderBy(p => p.Key);


            string requestUri = $"https://wbsapi.withings.net/measure?action=getmeas&userid={userId}&devtype={deviceType}&";

            requestUri += string.Join("&", oAuth_params.Select(kvp => kvp.Key + "=" + kvp.Value));

            var signature = OAuthUtility.BuildBasicParameters(AppCredentials.ConsumerKey, AppCredentials.ConsumerSecret, requestUri, HttpMethod.Get, this.AccessToken)
                            .First((KeyValuePair <string, string> p) => p.Key == "oauth_signature").Value;

            string json = await HttpClient.GetStringAsync(requestUri + "&oauth_signature=" + signature);

            var o = JObject.Parse(json);

            return(JsonConvert.DeserializeObject <IEnumerable <MeasureGroup> >(o["body"]["measuregrps"].ToString()));
        }
Beispiel #25
0
 private static void AssertCredentialsValues(AppCredentials creds, string expectedAppId, string expectedScope = AuthenticationConstants.ToChannelFromBotOAuthScope)
 {
     Assert.AreEqual(expectedAppId, creds.MicrosoftAppId);
     Assert.AreEqual(expectedScope, creds.OAuthScope);
 }
Beispiel #26
0
        public IActionResult SendCC([FromQuery] int studentDetailId)
        {
            Log.Information($"Sending CC email to {studentDetailId}");
            string        username     = User.Identity.Name.Split('\\')[User.Identity.Name.Split('\\').Length - 1];
            var           CCPermission = Context.ProSolutionPermissions.Where(i => i.UserName == username && i.IsAllowed == true && i.ObjectName == Config["CCProSolutionSecurityObject:ObjectName"] && i.ActionName == Config["CCProSolutionSecurityObject:ActionName"] && i.ObjectType == Config["CCProSolutionSecurityObject:ObjectType"]).FirstOrDefault();
            var           harrogateLetterPermission = Context.ProSolutionPermissions.Where(i => i.UserName == username && i.IsAllowed == true && i.ObjectName == Config["HOfferProSolutionSecurityObject:ObjectName"] && i.ActionName == Config["HOfferProSolutionSecurityObject:ActionName"] && i.ObjectType == Config["HOfferProSolutionSecurityObject:ObjectType"]).FirstOrDefault();
            var           generalLetterPermission   = Context.ProSolutionPermissions.Where(i => i.UserName == username && i.IsAllowed == true && i.ObjectName == Config["GOfferProSolutionSecurityObject:ObjectName"] && i.ActionName == Config["GOfferProSolutionSecurityObject:ActionName"] && i.ObjectType == Config["GOfferProSolutionSecurityObject:ObjectType"]).FirstOrDefault();
            StudentDetail student = Context.StudentDetail.Where(i => i.StudentDetailId == studentDetailId).SingleOrDefault();

            if (student == null)
            {
                ModelState.AddModelError("", "No Student specified - close this window and try again");
                Log.Error("No Student specified");
                return(View("Index", new StudentView()));
            }
            //var str = Request.Query["studentData"].FirstOrDefault();
            var sDetail = Context.StudentDetail.Where(i => i.StudentDetailId == studentDetailId).SingleOrDefault();

            try
            {
                if (sDetail.CriminalConvictionId != 2)
                {
                    ModelState.AddModelError("", $"Student {sDetail.RefNo} does not have a criminal conviction");
                    return(View("Index", MapStudentView(sDetail, true, CCPermission != null, harrogateLetterPermission != null, generalLetterPermission != null)));
                }
                var sentEmailControl = Context.CcsentMailControl.Where(i => i.StudentDetailId == sDetail.StudentDetailId).SingleOrDefault();
                if (sentEmailControl == null)
                {
                    sentEmailControl = new CcsentMailControl()
                    {
                        StudentDetailId = sDetail.StudentDetailId,
                        DateSent        = DateTime.Now,
                        Receipiant      = sDetail.Email,
                        Attempts        = 1
                    };
                    Context.Add(sentEmailControl);
                }
                else
                {
                    if (sentEmailControl.Attempts > 0)
                    {
                        sentEmailControl.Attempts++;
                    }
                    sentEmailControl.DateSent = DateTime.Now;
                    Context.Update(sentEmailControl);
                }
                Context.SaveChanges();

                var appCredential = Context.AppCredentials.Where(i => i.IdentityKey == sDetail.StudentDetailId.ToString() && i.SystemRef == "CC").SingleOrDefault();
                if (appCredential == null)
                {
                    appCredential = new AppCredentials()
                    {
                        ActivationWord   = getRandString(50),
                        IdentityKey      = sDetail.StudentDetailId.ToString(),
                        Expiry           = null,
                        SystemRef        = "CC",
                        ProtectionString = getRandString(10)
                    };
                    Context.Add(appCredential);
                }
                else
                {
                }
                Context.SaveChanges();

                var dispQueue = Context.CcdispatchQueue.Where(i => i.StudentDetailId == sDetail.StudentDetailId && i.SystemRef == "CC").SingleOrDefault();
                if (dispQueue == null)
                {
                    dispQueue = new CcdispatchQueue()
                    {
                        StudentDetailId = sDetail.StudentDetailId,
                        AddedBy         = User.Identity.Name,
                        DateStamp       = DateTime.Now,
                        Status          = 0,
                        SystemRef       = "CC"
                    };
                    Context.Add(dispQueue);
                }
                else
                {
                    dispQueue.DateStamp = DateTime.Now;
                    dispQueue.AddedBy   = User.Identity.Name;
                    dispQueue.Status    = 0;
                    Context.Update(dispQueue);
                }
                Context.SaveChanges();
                Log.Information($"Finished SendCC for {sDetail.RefNo} {ModelState.IsValid}");
                if (!ModelState.IsValid)
                {
                    foreach (var error in ModelState)
                    {
                        Log.Error($"{error}");
                    }
                }
                return(View("Index", MapStudentView(sDetail, true, CCPermission != null, harrogateLetterPermission != null, generalLetterPermission != null)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "An error has occurred");
                Log.Error(ex.Message);
                return(View("Index", MapStudentView(sDetail, true, CCPermission != null, harrogateLetterPermission != null, generalLetterPermission != null)));
            }
        }
Beispiel #27
0
        private async Task CreateConversationAsync(ITurnContext turnContext, string channelId, string serviceUrl, AppCredentials credentials, ConversationParameters conversationParameters, BotCallbackHandler callback, CancellationToken cancellationToken)
        {
            using (var connectorClient = new ConnectorClient(new Uri(serviceUrl), credentials))
            {
                var result = await connectorClient.Conversations.CreateConversationAsync(conversationParameters, cancellationToken).ConfigureAwait(false);

                // Create a conversation update activity to represent the result.
                var eventActivity = Activity.CreateEventActivity();
                eventActivity.Name         = ActivityEventNames.CreateConversation;
                eventActivity.ChannelId    = channelId;
                eventActivity.ServiceUrl   = serviceUrl;
                eventActivity.Id           = result.ActivityId ?? Guid.NewGuid().ToString("n");
                eventActivity.Conversation = new ConversationAccount(id: result.Id, tenantId: conversationParameters.TenantId);
                eventActivity.ChannelData  = conversationParameters.ChannelData;
                eventActivity.Recipient    = conversationParameters.Bot;

                using (var context = new TurnContext(turnContext.Adapter, (Activity)eventActivity))
                {
                    var claimsIdentity = new ClaimsIdentity();
                    claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AudienceClaim, credentials.MicrosoftAppId));
                    claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AppIdClaim, credentials.MicrosoftAppId));
                    claimsIdentity.AddClaim(new Claim(AuthenticationConstants.ServiceUrlClaim, serviceUrl));

                    //context.TurnState.Add<IIdentity>(BotIdentityKey, claimsIdentity);
                    //context.TurnState.Add(connectorClient);

                    //Middleware?  Forget about it in this little hack.
                    //await RunPipelineAsync(context, callback, cancellationToken).ConfigureAwait(false);
                    await callback(turnContext, cancellationToken).ConfigureAwait(false);

                    // Cleanup disposable resources in case other code kept a reference to it.
                    //context.TurnState.Set<IConnectorClient>(null);
                }
            }
        }
 public override Task <TokenResponse> GetUserTokenAsync(ITurnContext turnContext, AppCredentials appCredentials, string connectionName, string magicCode, CancellationToken cancellationToken)
 {
     return(Task.FromResult(_getUserTokenAction()));
 }
        public IActionResult SendCCee(string p1)
        {
            try
            {
                var f       = Request.Query["studentId"];
                var sDetail = ImmediateDB.StudentDetail.Where(i => i.RefNo == "").SingleOrDefault();

                var sentEmailControl = ImmediateDB.CcsentMailControl.Where(i => i.StudentDetailId == sDetail.StudentDetailId).SingleOrDefault();
                if (sentEmailControl == null)
                {
                    sentEmailControl = new CcsentMailControl()
                    {
                        StudentDetailId = sDetail.StudentDetailId,
                        DateSent        = DateTime.Now,
                        Receipiant      = sDetail.Email,
                        Attempts        = 1
                    };
                    ImmediateDB.Add(sentEmailControl);
                }
                else
                {
                    sentEmailControl.Attempts++;
                    sentEmailControl.DateSent = DateTime.Now;
                    ImmediateDB.Update(sentEmailControl);
                }
                ImmediateDB.SaveChanges();

                var appCredential = ImmediateDB.AppCredentials.Where(i => i.IdentityKey == sDetail.StudentDetailId.ToString() && i.SystemRef == "CC").SingleOrDefault();
                if (appCredential == null)
                {
                    appCredential = new AppCredentials()
                    {
                        ActivationWord   = getRandString(50),
                        IdentityKey      = sDetail.StudentDetailId.ToString(),
                        Expiry           = null,
                        SystemRef        = "CC",
                        ProtectionString = getRandString(10)
                    };
                    ImmediateDB.Add(appCredential);
                }
                else
                {
                }
                ImmediateDB.SaveChanges();

                var dispQueue = ImmediateDB.CcdispatchQueue.Where(i => i.StudentDetailId == sDetail.StudentDetailId).SingleOrDefault();
                if (dispQueue == null)
                {
                    dispQueue = new CcdispatchQueue()
                    {
                        StudentDetailId = sDetail.StudentDetailId,
                        AddedBy         = "",
                        DateStamp       = DateTime.Now,
                        Status          = 0
                    };
                    ImmediateDB.Add(dispQueue);
                }
                else
                {
                    dispQueue.DateStamp = DateTime.Now;
                    dispQueue.Status    = 0;
                    ImmediateDB.Update(dispQueue);
                }
                ImmediateDB.SaveChanges();
                return(View());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
 public HomeController(IConfiguration configuration, IHttpClientFactory httpClientFactory, AppCredentials botCredentials)
 {
     _configuration      = configuration;
     this.botCredentials = botCredentials;
     this.httpClient     = httpClientFactory.CreateClient();
 }