Пример #1
0
        private async Task ApiCall(string url)
        {
            try
            {
                IConfidentialClientApplication confidentialClientApplication =
                    ConfidentialClientApplicationBuilder
                    .Create(Configuration["AzureAd:ClientId"])
                    .WithTenantId(Configuration["AzureAd:TenantId"])
                    .WithClientSecret(Configuration["AzureAd:ClientSecret"])
                    .Build();
                string[]             scopes = new string[] { "https://graph.microsoft.com/.default" };
                AuthenticationResult result = null;
                result = await confidentialClientApplication.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                var res        = await apiCaller
                                 .CallWebApiAndProcessResultASync(
                    url,
                    result.AccessToken
                    );

                ProcessGraphUsers(res);
                if (res.Properties().FirstOrDefault(p => p.Name == "@odata.nextLink") != null)
                {
                    await ApiCall(res.Properties().First(p => p.Name == "@odata.nextLink").Value.ToString());
                }
            }
            catch (Exception ex)
            {
                Telemetry.TrackException(ex);
                ToastService.ShowWarning("Fout bij het ophalen van de gebruikers.");
            }
        }
Пример #2
0
        //Get events of specific user with Graph api
        public static async void getEvents(HttpClient httpClient, string accessToken, Action <JObject> Display)
        {
            var apiCaller = new ProtectedApiCallHelper(httpClient);
            await apiCaller.CallWebApiAndProcessResultASync($"https://graph.microsoft.com/v1.0/users/[email protected]/events", accessToken, Display);

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
        }
Пример #3
0
        /// <summary>
        /// Retrieves and populates permissions descriptions from a Service Principal.
        /// </summary>
        /// <param name="config">The application configuration settings.</param>
        /// <param name="result">The JSON response of the permissions and their descriptions retrieved from the Service Prinicpal.</param>
        /// <param name="version">The version of the API from which to fetch the scopes descriptions from the Service Principal.</param>
        private static void PopulateScopesDescriptions(PermissionsAppConfig config,
                                                       AuthenticationResult result,
                                                       string version)
        {
            string webApiUrl = $"{config.ApiUrl}{version}/serviceprincipals?$filter=appId eq '{config.ServicePrincipalId}'";
            var    spJson    = ProtectedApiCallHelper
                               .CallWebApiAsync(webApiUrl, result.AccessToken)
                               .GetAwaiter().GetResult();

            if (string.IsNullOrEmpty(spJson))
            {
                throw new ArgumentNullException(nameof(spJson), $"The call to fetch the Service Principal returned empty data. URL: {webApiUrl} ");
            }

            var spJsonResponse = PermissionsFormatHelper.FormatServicePrincipalResponse(spJson, config);

            // Retrieve the top level scope dictionary
            var spValue = JsonConvert.DeserializeObject <JObject>(spJsonResponse).Value <JArray>(config.TopLevelDictionaryName);

            if (spValue == null)
            {
                throw new ArgumentNullException(nameof(config.TopLevelDictionaryName), $"Attempt to retrieve the top-level dictionary returned empty data." +
                                                $"Name: {config.TopLevelDictionaryName}");
            }

            /* Fetch permissions defined in the second level dictionary(ies),
             * e.g. appRoles, oauth2PermissionScopes --> 2nd level dictionary keys
             */
            foreach (string scopeName in config.ScopesNames)
            {
                // Retrieve all scopes descriptions for a given 2nd level dictionary retrieved from the Service Principal
                var scopeDescriptions = spValue.First.Value <JArray>(scopeName)?.ToObject <List <Dictionary <string, object> > >();

                if (scopeDescriptions == null)
                {
                    continue;
                }

                // Add a key to the reference dictionary (if not present)
                if (!_scopesDescriptions.ContainsKey(scopeName))
                {
                    _scopesDescriptions.Add(scopeName, new List <Dictionary <string, object> >());
                }

                /* Add each of the scope description from SP to the current key in the
                 * reference dictionary
                 */
                foreach (var scopeDesc in scopeDescriptions)
                {
                    /* Add only unique scopes (there might be duplicated scopes in both v1.0 and beta)
                     * Uniqueness identified by id of the scope description
                     */
                    bool newScope = _uniqueScopes.Add(scopeDesc["id"].ToString());
                    if (newScope)
                    {
                        _scopesDescriptions[scopeName].Add(scopeDesc);
                    }
                }
            }
        }
Пример #4
0
        public async Task <ActionResult <JObject> > Get(string groupid)
        {
            if (string.IsNullOrEmpty(groupid))
            {
                return(new JObject {
                    "You must include a group id"
                });
            }
            AuthenticationConfig           config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
            IConfidentialClientApplication app;

            app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                  .WithClientSecret(config.ClientSecret)
                  .WithAuthority(new Uri(config.Authority))
                  .Build();
// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
            // application permissions need to be set statically (in the portal or by PowerShell), and then granted by
            // a tenant administrator
            string[]             scopes      = new string[] { "https://graph.microsoft.com/.default" };
            JObject              returnValue = new JObject();
            AuthenticationResult result      = null;

            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Token acquired");
                Console.ResetColor();
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Scope provided is not supported");
                Console.ResetColor();
            }

            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                // await apiCaller.CallWebApiAndProcessResultASync($"https://graph.microsoft.com/v1.0/groups/{groupid}", result.AccessToken, Display);
                returnValue = await apiCaller.CallWebApiASync($"https://graph.microsoft.com/v1.0/groups/{groupid}", result.AccessToken);
            }



            return(returnValue);
        }
Пример #5
0
        /// <summary>
        /// 获得上传url
        /// </summary>
        /// <param name="path"></param>
        /// <param name="siteName"></param>
        /// <returns></returns>
        public async Task <string> GetUploadUrl(string path, string siteName = "onedrive")
        {
            var drive         = siteName != "onedrive" ? _graph.Sites[GetSiteId(siteName)].Drive : _graph.Me.Drive;
            var requestUrl    = drive.Root.ItemWithPath(path).CreateUploadSession().Request().RequestUrl;
            var apiCallHelper = new ProtectedApiCallHelper(new HttpClient());
            var uploadUrl     = "";
            await apiCallHelper.CallWebApiAndProcessResultASync(requestUrl, _accountService.GetToken(), o =>
            {
                uploadUrl = o["uploadUrl"].ToString();
            }, ProtectedApiCallHelper.Method.Post);

            return(uploadUrl);
        }
Пример #6
0
        public async Task <ActionResult> TodoList()
        {
            ViewBag.Message = "Todo List";
            string certificateFile = Server.MapPath($"~/{ConfigurationManager.AppSettings["CertificateFileName"]}");
            var    cert            = new X509Certificate2(certificateFile, ConfigurationManager.AppSettings["CertificatePassword"]);
            var    handler         = new HttpClientHandler();

            handler.ClientCertificates.Add(cert);
            var httpClient = new HttpClient(handler);
            //httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["TodoListBaseAddress"].ToString());
            var apiCaller = new ProtectedApiCallHelper(httpClient);

            //            ApiResponse result = await apiCaller.CallWebApiAndProcessResultASync("/api/todolist");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                   | SecurityProtocolType.Tls11
                                                   | SecurityProtocolType.Tls12
                                                   | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"{ConfigurationManager.AppSettings["TodoListBaseAddress"].ToString()}/api/todolist"),
                Method     = HttpMethod.Get,
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Add("Ocp-Apim-Trace", "true");
            request.Headers.Add("Ocp-Apim-Subscription-Key", "25e68b24928848cab405d251dfd176e2");
            List <Todo> data   = null;
            APIResponse result = await apiCaller.CallWebApiAndProcessResultASync(request);

            if (result.Result as List <JObject> != null)
            {
                data = new List <Todo>();
                foreach (var item in result.Result as List <JObject> )
                {
                    Todo todoItem = item.ToObject <Todo>();
                    data.Add(todoItem);
                }
            }
            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                ViewBag.ErrorMessage = $"Error Code: {result.ErrorCode}, ErrorMessage:{result.ErrorMessage}";
            }
            return(View(data));
        }
Пример #7
0
        public async Task <ActionResult> ValidateCert()
        {
            string certificateFile = Server.MapPath($"~/{ConfigurationManager.AppSettings["KCCCertificateFileName"]}");
            var    cert            = new X509Certificate2(certificateFile, ConfigurationManager.AppSettings["KCCCertificatePassword"]);
            var    handler         = new HttpClientHandler();

            handler.ClientCertificates.Add(cert);
            var httpClient = new HttpClient(handler);
            //httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["TodoListBaseAddress"].ToString());
            var apiCaller = new ProtectedApiCallHelper(httpClient);

            //            ApiResponse result = await apiCaller.CallWebApiAndProcessResultASync("/api/todolist");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                   | SecurityProtocolType.Tls11
                                                   | SecurityProtocolType.Tls12
                                                   | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"{ConfigurationManager.AppSettings["ApiGatewayBaseAddress"]}/ShippingRates/ByName/LTLWeightCutoff"),
                Method     = HttpMethod.Get,
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Add("Ocp-Apim-Trace", "true");
            request.Headers.Add("Ocp-Apim-Subscription-Key", ConfigurationManager.AppSettings["ApiGatewaySubsKey"]);

            APIResponse result = await apiCaller.CallWebApiAndProcessResultASync(request);

            ShippingRate rate = null;

            if (result.Result != null)
            {
                ViewBag.Result = result.Result.ToString();
                rate           = result.Result as ShippingRate;
            }

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                ViewBag.ErrorMessage = $"Error Code: {result.ErrorCode}, ErrorMessage:{result.ErrorMessage}";
            }
            return(View(rate));
        }
Пример #8
0
        /// <summary>
        /// 添加 SharePoint Site-ID 到数据库
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="dominName"></param>
        /// <returns></returns>
        public async Task AddSiteId(string siteName, string nickName)
        {
            Site site = new Site();

            //使用 Onedrive
            if (siteName == "onedrive")
            {
                site.Name     = siteName;
                site.NickName = nickName;
            }
            else
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(20);
                    var apiCaller = new ProtectedApiCallHelper(httpClient);
                    await apiCaller.CallWebApiAndProcessResultASync($"{Configuration.GraphApi}/v1.0/sites/{Configuration.DominName}:/sites/{siteName}", GetToken(), (result) =>
                    {
                        site.SiteId   = result.Properties().Single((prop) => prop.Name == "id").Value.ToString();
                        site.Name     = result.Properties().Single((prop) => prop.Name == "name").Value.ToString();
                        site.NickName = nickName;
                    });
                }
            }
            if (!SiteContext.Sites.Any(s => s.SiteId == site.SiteId))
            {
                //若是首次添加则设置为默认的驱动器
                using (SettingService setting = new SettingService(new SettingContext()))
                {
                    if (SiteContext.Sites.Count() == 0)
                    {
                        await setting.Set("DefaultDrive", site.Name);
                    }
                }
                await SiteContext.Sites.AddAsync(site);

                await SiteContext.SaveChangesAsync();
            }
            else
            {
                throw new Exception("站点已被创建");
            }
        }
        public async Task <AlertsResponse> GetAlerts()
        {
            var result = await AuthenticationService.AcquireAzureTokenForClient(_app, _appConfigService.Config.AlertsConfig.Scopes);

            if (result != null)
            {
                var httpClient   = new HttpClient();
                var apiCaller    = new ProtectedApiCallHelper(httpClient);
                var url          = _appConfigService.Config.AlertsConfig.GetFullUrl(_appConfigService.Config.AzureConfig.SubscriptionId);
                var jsonResponse = await apiCaller.CallWebApiAndProcessResultASync(url, result.AccessToken);

                if (jsonResponse != null)
                {
                    var alerts = JsonConvert.DeserializeObject <AlertsResponse>(jsonResponse);

                    return(alerts);
                }
            }

            return(null);
        }
Пример #10
0
        public async Task <IActionResult> Submit([FromBody] FieldData body)
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication
            bool isUsingClientSecret = AppUsesClientSecret(config);

            // Even if this is a console application here, a daemon application is a confidential client application
            IConfidentialClientApplication app;

            if (isUsingClientSecret)
            {
                app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                      .WithClientSecret(config.ClientSecret)
                      .WithAuthority(new Uri(config.Authority))
                      .Build();
            }

            else
            {
                X509Certificate2 certificate = ReadCertificate(config.CertificateName);
                app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                      .WithCertificate(certificate)
                      .WithAuthority(new Uri(config.Authority))
                      .Build();
            }

            // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
            // application permissions need to be set statically (in the portal or by PowerShell), and then granted by
            // a tenant administrator.
            string[] scopes = new string[] { $"{config.ApiUrl}.default" };

            AuthenticationResult result = null;

            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                return(BadRequest("Scope not supported"));
            }

            if (result != null)
            {
                var SOBListLocation    = $"{config.CpscSharepoint},c0cefe40-beeb-41a9-b4f5-9960bcfa010b,fbb78c64-1220-42fe-a319-94c493a9a105/lists/6f53c37b-d6ba-46c3-91a9-2e942a984af9/items";
                var webapiUrl          = $"{config.ApiUrl}v1.0/sites/{SOBListLocation}";
                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, webapiUrl);
                httpRequestMessage.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
                var httpClient = new HttpClient();

                var apiCaller = new ProtectedApiCallHelper(httpClient);
                var res       = await apiCaller.CallWebApiAndProcessResultASync(httpRequestMessage, result.AccessToken);

                return(Ok(res));
                // await apiCaller.AddToSiteList("siteid", "listId", "payload", Display);//
            }
            else
            {
                return(Ok("result is null"));
            }
        }
 public MyInformation(IPublicClientApplication app, HttpClient client, string microsoftGraphBaseEndpoint)
 {
     tokenAcquisitionHelper     = new PublicAppUsingDeviceCodeFlow(app);
     protectedApiCallHelper     = new ProtectedApiCallHelper(client);
     MicrosoftGraphBaseEndpoint = microsoftGraphBaseEndpoint;
 }