/// <summary>
        /// Resolves the type of the Authentication Provider to create
        /// </summary>
        /// <param name="option">The configuration options for the target Authentication Provider</param>
        /// <returns>The type of the target Authentication Provider</returns>
        private static Type ResolveAuthenticationProviderType(PnPCoreAuthenticationCredentialConfigurationOptions option)
        {
            // Determine the Authentication Provider type to create
            Type providerType = null;

            if (option.X509Certificate != null)
            {
                providerType = typeof(X509CertificateAuthenticationProvider);
            }
            else if (option.CredentialManager != null)
            {
                providerType = typeof(CredentialManagerAuthenticationProvider);
            }
            else if (option.OnBehalfOf != null)
            {
                providerType = typeof(OnBehalfOfAuthenticationProvider);
            }
            else if (option.UsernamePassword != null)
            {
                providerType = typeof(UsernamePasswordAuthenticationProvider);
            }
            else if (option.DeviceCode != null)
            {
                providerType = typeof(DeviceCodeAuthenticationProvider);
            }
            else
            {
                providerType = typeof(InteractiveAuthenticationProvider);
            }

            return(providerType);
        }
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            // We need the DeviceCode options
            if (options.DeviceCode == null)
            {
                throw new ConfigurationErrorsException(
                          PnPCoreAuthResources.DeviceCodeAuthenticationProvider_InvalidConfiguration);
            }

            ClientId    = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId    = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;
            RedirectUri = options.DeviceCode.RedirectUri ?? AuthGlobals.DefaultRedirectUri;

            // Build the MSAL client
            publicClientApplication = PublicClientApplicationBuilder
                                      .Create(ClientId)
                                      .WithPnPAdditionalAuthenticationSettings(
                options.DeviceCode.AuthorityUri,
                RedirectUri,
                TenantId,
                options.Environment)
                                      .WithHttpClientFactory(msalHttpClientFactory)
                                      .Build();

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.DeviceCodeAuthenticationProvider_LogInit);
        }
예제 #3
0
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            // We need the OnBehalfOf options
            if (options.OnBehalfOf == null)
            {
                throw new ConfigurationErrorsException(
                          PnPCoreAuthResources.OnBehalfOfAuthenticationProvider_InvalidConfiguration);
            }

            // We need the certificate thumbprint
            if (string.IsNullOrEmpty(options.OnBehalfOf.ClientSecret) && string.IsNullOrEmpty(options.OnBehalfOf.Thumbprint))
            {
                throw new ConfigurationErrorsException(PnPCoreAuthResources.OnBehalfOfAuthenticationProvider_InvalidClientSecretOrCertificate);
            }

            ClientId = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;
            if (!string.IsNullOrEmpty(options.OnBehalfOf.Thumbprint))
            {
                // We prioritize the X.509 certificate, if any
                Certificate = X509CertificateUtility.LoadCertificate(
                    options.OnBehalfOf.StoreName,
                    options.OnBehalfOf.StoreLocation,
                    options.OnBehalfOf.Thumbprint);
            }
            else if (!string.IsNullOrEmpty(options.OnBehalfOf.ClientSecret))
            {
                // Otherwise we fallback to the client secret
                ClientSecret = options.OnBehalfOf.ClientSecret.ToSecureString();
            }

            if (Certificate != null)
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(ClientId)
                                                .WithCertificate(Certificate)
                                                .WithPnPAdditionalAuthenticationSettings(
                    options.OnBehalfOf.AuthorityUri,
                    options.OnBehalfOf.RedirectUri,
                    TenantId)
                                                .Build();
            }
            else
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(ClientId)
                                                .WithClientSecret(ClientSecret.ToInsecureString())
                                                .WithPnPAdditionalAuthenticationSettings(
                    options.OnBehalfOf.AuthorityUri,
                    options.OnBehalfOf.RedirectUri,
                    TenantId)
                                                .Build();
            }

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.OnBehalfOfAuthenticationProvider_LogInit);
        }
        /// <summary>
        /// Initializes the configuration options for the target Authentication Provider
        /// </summary>
        /// <param name="provider">The target Authentication Provider</param>
        /// <param name="option">The configuration options for the target Authentication Provider</param>
        private static void InitProviderOptions(IAuthenticationProvider provider, PnPCoreAuthenticationCredentialConfigurationOptions option)
        {
            switch (provider)
            {
            case X509CertificateAuthenticationProvider x509Certificate:
                x509Certificate.ClientId    = option.ClientId;
                x509Certificate.TenantId    = option.TenantId;
                x509Certificate.Certificate = X509CertificateUtility.LoadCertificate(
                    option.X509Certificate.StoreName,
                    option.X509Certificate.StoreLocation,
                    option.X509Certificate.Thumbprint);
                break;

            case ExternalAuthenticationProvider aspNetCore:
                aspNetCore.ClientId = option.ClientId;
                aspNetCore.TenantId = option.TenantId;
                break;

            case CredentialManagerAuthenticationProvider credentialManager:
                credentialManager.ClientId = option.ClientId;
                credentialManager.TenantId = option.TenantId;
                credentialManager.CredentialManagerName = option.CredentialManager.CredentialManagerName;
                break;

            case OnBehalfOfAuthenticationProvider onBehalfOf:
                onBehalfOf.ClientId     = option.ClientId;
                onBehalfOf.TenantId     = option.TenantId;
                onBehalfOf.ClientSecret = option.OnBehalfOf.ClientSecret.ToSecureString();
                break;

            case UsernamePasswordAuthenticationProvider usernamePassword:
                usernamePassword.ClientId = option.ClientId;
                usernamePassword.TenantId = option.TenantId;
                usernamePassword.Username = option.UsernamePassword.Username;
                usernamePassword.Password = option.UsernamePassword.Password.ToSecureString();
                break;

            case InteractiveAuthenticationProvider interactive:
                interactive.ClientId    = option.ClientId;
                interactive.TenantId    = option.TenantId;
                interactive.RedirectUri = option.Interactive.RedirectUri;
                break;

            case DeviceCodeAuthenticationProvider deviceCode:
                deviceCode.ClientId    = option.ClientId;
                deviceCode.TenantId    = option.TenantId;
                deviceCode.RedirectUri = option.Interactive.RedirectUri;
                break;
            }
        }
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        public PersistentInteractiveAuthenticationProvider(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            ClientId    = options.ClientId;
            TenantId    = options.TenantId;
            RedirectUri = options.Interactive?.RedirectUri;

            // Build the MSAL client
            publicClientApplication = PublicClientApplicationBuilder
                                      .Create(ClientId)
                                      .WithPnPAdditionalAuthenticationSettings(
                options.Interactive?.AuthorityUri,
                RedirectUri,
                TenantId)
                                      .Build();
        }
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            // We need the CredentialManager options
            if (options.CredentialManager == null)
            {
                throw new ArgumentException(
                          PnPCoreAuthResources.CredentialManagerAuthenticationProvider_InvalidConfiguration,
                          nameof(options));
            }

            if (string.IsNullOrEmpty(options.CredentialManager.CredentialManagerName))
            {
                throw new ConfigurationErrorsException(PnPCoreAuthResources.CredentialManagerAuthenticationProvider_InvalidCredentialManagerName);
            }

            // Retrieve credentials from the Credential Manager
            CredentialManagerName = options.CredentialManager.CredentialManagerName;
            var credentials = CredentialManager.GetCredential(CredentialManagerName);

            if (credentials == null)
            {
                throw new ConfigurationErrorsException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                     PnPCoreAuthResources.CredentialManagerAuthenticationProvider_CredentialManagerEntryDoesNotExist,
                                                                     CredentialManagerName));
            }

            ClientId = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;

            var usernamePasswordOptions = new PnPCoreAuthenticationCredentialConfigurationOptions
            {
                ClientId         = ClientId,
                TenantId         = TenantId,
                Environment      = options.Environment,
                UsernamePassword = new PnPCoreAuthenticationUsernamePasswordOptions
                {
                    Username = credentials.UserName,
                    Password = credentials.Password,
                }
            };

            // Configure the inner instance of UsernamePasswordAuthenticationProvider
            usernamePasswordProvider.Init(usernamePasswordOptions);

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.CredentialManagerAuthenticationProvider_LogInit,
                                options.CredentialManager.CredentialManagerName);
        }
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            ClientId    = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId    = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;
            RedirectUri = options.Interactive?.RedirectUri ?? AuthGlobals.DefaultRedirectUri;

            // Build the MSAL client
            publicClientApplication = PublicClientApplicationBuilder
                                      .Create(ClientId)
                                      .WithPnPAdditionalAuthenticationSettings(
                options.Interactive?.AuthorityUri,
                RedirectUri,
                TenantId)
                                      .Build();

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.InteractiveAuthenticationProvider_LogInit);
        }
예제 #8
0
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            // We need the UsernamePassword options
            if (options.UsernamePassword == null)
            {
                throw new ConfigurationErrorsException(
                          PnPCoreAuthResources.UsernamePasswordAuthenticationProvider_InvalidConfiguration);
            }

            // We need the Username
            if (string.IsNullOrEmpty(options.UsernamePassword.Username))
            {
                throw new ConfigurationErrorsException(PnPCoreAuthResources.UsernamePasswordAuthenticationProvider_InvalidUsername);
            }

            // We need the Password
            if (string.IsNullOrEmpty(options.UsernamePassword.Password))
            {
                throw new ConfigurationErrorsException(PnPCoreAuthResources.UsernamePasswordAuthenticationProvider_InvalidPassword);
            }

            ClientId = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;
            Username = options.UsernamePassword.Username;
            Password = options.UsernamePassword.Password.ToSecureString();

            // Build the MSAL client
            publicClientApplication = PublicClientApplicationBuilder
                                      .Create(ClientId)
                                      .WithPnPAdditionalAuthenticationSettings(
                options.UsernamePassword.AuthorityUri,
                options.UsernamePassword.RedirectUri,
                TenantId,
                options.Environment)
                                      .WithHttpClientFactory(msalHttpClientFactory)
                                      .Build();

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.UsernamePasswordAuthenticationProvider_LogInit,
                                options.UsernamePassword.Username);
        }
        /// <summary>
        /// Initializes the X509Certificate Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            // We need the X509Certificate options
            if (options.X509Certificate == null)
            {
                throw new ConfigurationErrorsException(
                          PnPCoreAuthResources.X509CertificateAuthenticationProvider_InvalidConfiguration);
            }

            // We need the certificate thumbprint
            if (options.X509Certificate.Certificate == null && string.IsNullOrEmpty(options.X509Certificate.Thumbprint))
            {
                throw new ConfigurationErrorsException(PnPCoreAuthResources.X509CertificateAuthenticationProvider_InvalidCertificateOrThumbprint);
            }

            ClientId    = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId    = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;
            Certificate = options.X509Certificate.Certificate ?? X509CertificateUtility.LoadCertificate(
                options.X509Certificate.StoreName,
                options.X509Certificate.StoreLocation,
                options.X509Certificate.Thumbprint);

            confidentialClientApplication = ConfidentialClientApplicationBuilder
                                            .Create(ClientId)
                                            .WithCertificate(Certificate)
                                            .WithHttpClientFactory(msalHttpClientFactory)
                                            .WithPnPAdditionalAuthenticationSettings(
                options.X509Certificate.AuthorityUri,
                options.X509Certificate.RedirectUri,
                TenantId,
                options.Environment)
                                            .Build();

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.X509CertificateAuthenticationProvider_LogInit,
                                options.X509Certificate.Thumbprint,
                                options.X509Certificate.StoreName,
                                options.X509Certificate.StoreLocation);
        }
예제 #10
0
 /// <summary>
 /// Initializes the Authentication Provider
 /// </summary>
 internal abstract void Init(PnPCoreAuthenticationCredentialConfigurationOptions options);
 /// <summary>
 /// Initializes the Authentication Provider
 /// </summary>
 /// <param name="options">The options to use</param>
 internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
 {
     // Log the initialization information
     Log?.LogInformation(PnPCoreAuthResources.ExternalAuthenticationProvider_LogInit);
 }
예제 #12
0
        static async Task Main(string[] args)
        {
            var host = Host.CreateDefaultBuilder()
                       .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddEventSourceLogger();
                logging.AddConsole();
            })
                       .ConfigureServices((hostingContext, services) =>
            {
                // Add the PnP Core SDK services
                services.AddPnPCore(options => {
                    // You can explicitly configure all the settings, or you can
                    // simply use the default values

                    options.PnPContext.GraphFirst = true;
                });
            })
                       // Let the builder know we're running in a console
                       .UseConsoleLifetime()
                       // Add services to the container
                       .Build();

            await host.StartAsync();

            using (var scope = host.Services.CreateScope())
            {
                var pnpContextFactory = scope.ServiceProvider.GetRequiredService <IPnPContextFactory>();
                // Define the relevant Authentication options
                var pnpOptions = new PnPCoreAuthenticationCredentialConfigurationOptions
                {
                    TenantId    = "{TenantId}", // Set to the target tenant id
                    ClientId    = "{ClientId}", // Set to the ClientId obtained from the Azure app
                    Interactive = new PnPCoreAuthenticationInteractiveOptions
                    {
                        RedirectUri = new Uri("http://localhost")  // return to localhost is fine for a console app
                    }
                };

                // Replace {cache_file_name} with a meaningful name
                // Replace {cache_destination_directory} with a path to the folder you want to persist the cache
                var storageProperties = new StorageCreationPropertiesBuilder("{cache_file_name}", "{cache_destination_directory}")
                                        .Build();

                var authenticationProvider = new PersistentInteractiveAuthenticationProvider(pnpOptions);
                // Register Authenticator token cache with the Msal persistent one
                await authenticationProvider.RegisterTokenStorageAsync(storageProperties);

                #region Interactive GET's
                // Replace {sharepoint_address} with your target SP url
                using (var context = await pnpContextFactory.CreateAsync(new Uri("{sharepoint_address}"), authenticationProvider))
                {
                    // ================================================================
                    // Getting data - everything is async!
                    // Same programming model, regardless of wether under the covers Microsoft Graph is used or SharePoint REST

                    // Interactive GET samples

                    // Retrieving web with lists and masterpageurl loaded ==> SharePoint REST query
                    var web = await context.Web.GetAsync(p => p.Title, p => p.Lists, p => p.MasterUrl);

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("===Web (REST)===");
                    Console.WriteLine($"Title: {web.Title}");
                    Console.WriteLine($"# Lists: {web.Lists.Length}");
                    Console.WriteLine($"Master page url: {web.MasterUrl}");
                    Console.ResetColor();

                    // Getting the team connected to this Modern Team site ==> Microsoft Graph query
                    var team = await context.Team.GetAsync();

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("===Team (Graph v1)===");
                    Console.WriteLine($"Name: {team.DisplayName}");
                    Console.WriteLine($"Visibility: {team.Visibility}");
                    Console.WriteLine($"Funsettings.AllowGiphy: {team.FunSettings.AllowGiphy}");
                    Console.ResetColor();
                }
                #endregion
            }

            host.Dispose();
        }