Ejemplo n.º 1
0
        private static async Task RunAsync()
        {
            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. The Graph endpoint may have to be changed for national cloud scenarios, refer to
            // https://docs.microsoft.com/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            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/users", result.AccessToken, Display);
            }
        }
Ejemplo n.º 2
0
        private static async Task RunAsync()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile();

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


            IPublicClientApplication app = PublicClientApplicationBuilder
                                           .Create(config.ClientId)
                                           .WithAuthority(config.Authority)
                                           .WithDefaultRedirectUri()
                                           .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" };

            AuthenticationResult result = null;
            var accounts = await app.GetAccountsAsync();

            result = await AcquireByDeviceCodeAsync(app, scopes);

            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebApiAndProcessResultASync("https://graph.microsoft.com/v1.0/users", result.AccessToken, Display);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Calls MS Graph REST API using an authenticated Http client
        /// </summary>
        /// <param name="config"></param>
        /// <param name="app"></param>
        /// <param name="scopes"></param>
        /// <returns></returns>
        private static async Task CallMSGraph(AuthenticationConfig config, IConfidentialClientApplication app, string[] scopes)
        {
            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();
            }

            // The following example uses a Raw Http call
            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);
            }
        }
Ejemplo n.º 4
0
        private static async Task RunAsync()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
            var cert    = new X509Certificate2(config.CertificateFileName, config.CertificatePassword);
            var handler = new HttpClientHandler();

            handler.ClientCertificates.Add(cert);
            var httpClient = new HttpClient(handler);
            var apiCaller  = new ProtectedApiCallHelper(httpClient);
            await apiCaller.CallWebApiAndProcessResultASync($"{config.TodoListBaseAddress}/api/todolist", Display);
        }
Ejemplo n.º 5
0
        private static async Task ExecuteLandingPageMiddlewareAPIAsync(string userPrincipalName)
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json", "TodoListService");

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

#if !VariationWithCertificateCredentials
            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();
#endif

            // 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://vodafoneitc.onmicrosoft.com/dc0b1790-bf49-4501-bf20-cedb62af0b6c/.default" };

            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);
                Console.WriteLine(await GetLandingPageMiddlewareAPIUrl(userPrincipalName));
                await apiCaller.CallWebApiAndProcessResultASync(await GetLandingPageMiddlewareAPIUrl(userPrincipalName), result.AccessToken, Display, HttpMethod.Get);
            }
        }
Ejemplo n.º 6
0
        private static async Task RunAsync()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            // Load the certificate
            ICertificateLoader certificateLoader = new DefaultCertificateLoader();

            certificateLoader.LoadIfNeeded(config.Certificate);

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

            app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                  .WithCertificate(config.Certificate.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();

                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($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);
            }
        }
        private static async Task RunAsync()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            // Even if this is a console application here, a daemon application is a confidential client application
            ClientCredential clientCredentials;

#if !VariationWithCertificateCredentials
            clientCredentials = new ClientCredential(config.ClientSecret);
#else
            X509Certificate2 certificate = ReadCertificate(config.CertificateName);
            clientCredentials = new ClientCredential(new ClientAssertionCertificate(certificate));
#endif
            var app = new ConfidentialClientApplication(config.ClientId, config.Authority, "https://daemon", clientCredentials, null, new TokenCache());

            // 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" };

            AuthenticationResult result = null;
            try
            {
                result = await app.AcquireTokenForClientAsync(scopes);
            }
            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
            }

            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebApiAndProcessResultASync("https://graph.microsoft.com/v1.0/users", result.AccessToken, Display);
            }
        }
Ejemplo n.º 8
0
        private static async Task RunAsync()
        {
            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();

                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 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);
                var body = new FieldData()
                {
                    fields = new FieldData.Fields()
                    {
                        Title        = "test",
                        Organization = "CPCSC",
                        Comments     = "Test",
                        Message      = "new Product",
                        Email        = "*****@*****.**",
                        Phone        = "301-504-7804",
                        Source       = "sharepointOnline-GraphAPI"
                    }
                };
                var jsonBody = JsonSerializer.Serialize(body);
                Console.WriteLine(jsonBody);
                httpRequestMessage.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                var httpClient = new HttpClient();

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

                Display(createdResult);

                // await apiCaller.AddToSiteList("siteid", "listId", "payload", Display);//
            }
        }
Ejemplo n.º 9
0
        private static async Task RunAsync()
        {
            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))
                      .WithExperimentalFeatures() // for PoP
                      .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.TodoListScope };

            AuthenticationResult result = null;
            string popUri = $"{config.TodoListBaseAddress}/api/todolist";

            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .WithProofOfPossession(new PoPAuthenticationConfiguration(new Uri(popUri))
                {
                    HttpMethod = HttpMethod.Get
                })
                         .ExecuteAsync();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Token acquired \n");
                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(popUri, result, Display);
            }
        }
Ejemplo n.º 10
0
        private static async Task RunAsync()
        {
            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();

                //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($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);
                //await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users/[email protected]/events", result.AccessToken, Display);
                //await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users/[email protected]/calendarView?startDateTime=2020-09-01T16:00:00.0000000&endDateTime=2020-12-07T16:00:00.0000000", result.AccessToken, Display);
                //await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users/[email protected]/calendarView?startDateTime=2020-09-01T16:00:00.0000000&endDateTime=2020-12-07T16:00:00.0000000", result.AccessToken, Display);
                //await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users//[email protected]/calendargroup/calendars/calendarView?startDateTime=2020-09-01T16:00:00.0000000&endDateTime=2020-12-07T16:00:00.0000000", result.AccessToken, Display);
                //await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/me/calendar", result.AccessToken, Display);

                await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users/[email protected]/calendar/getSchedule", result.AccessToken, Display);
            }
        }