Beispiel #1
0
        internal static PnPConnection CreateWithCert(Uri url, string clientId, string tenant, string tenantAdminUrl, AzureEnvironment azureEnvironment, X509Certificate2 certificate, bool certificateFromFile = false)
        {
            PnP.Framework.AuthenticationManager authManager = null;
            if (PnPConnection.CachedAuthenticationManager != null)
            {
                authManager = PnPConnection.CachedAuthenticationManager;
                PnPConnection.CachedAuthenticationManager = null;
            }
            else
            {
                authManager = PnP.Framework.AuthenticationManager.CreateWithCertificate(clientId, certificate, tenant, azureEnvironment: azureEnvironment);
            }
            using (authManager)
            {
                var clientContext = authManager.GetContext(url.ToString());
                var context       = PnPClientContext.ConvertFrom(clientContext);

                var connectionType = ConnectionType.O365;

                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }

                var spoConnection = new PnPConnection(context, connectionType, null, clientId, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.ClientIDCertificate)
                {
                    ConnectionMethod = ConnectionMethod.AzureADAppOnly,
                    Certificate      = certificate,
                    Tenant           = tenant,
                    DeleteCertificateFromCacheOnDisconnect = certificateFromFile,
                    AzureEnvironment = azureEnvironment
                };
                return(spoConnection);
            }
        }
        internal static PnPConnection CreateWithAccessToken(Uri url, string accessToken, string tenantAdminUrl)
        {
            using (var authManager = new PnP.Framework.AuthenticationManager(new System.Net.NetworkCredential("", accessToken).SecurePassword))
            {
                PnPClientContext context        = null;
                ConnectionType   connectionType = ConnectionType.O365;
                if (url != null)
                {
                    context = PnPClientContext.ConvertFrom(authManager.GetContext(url.ToString()));
                    context.ApplicationName         = Resources.ApplicationName;
                    context.DisableReturnValueCache = true;
                    context.ExecutingWebRequest    += (sender, e) =>
                    {
                        e.WebRequestExecutor.WebRequest.UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version} ({System.Environment.OSVersion.VersionString})";
                    };
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }

                var connection = new PnPConnection(context, connectionType, null, url != null ? url.ToString() : null, tenantAdminUrl, PnPPSVersionTag, InitializationType.Token);
                return(connection);
            }
        }
        internal static PnPConnection CreateWithWeblogin(Uri url, string tenantAdminUrl, bool clearCookies, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (Utilities.OperatingSystem.IsWindows())
            {
                // Log in to a specific page on the tenant which is known to be performant
                var webLoginClientContext = BrowserHelper.GetWebLoginClientContext(url.ToString(), clearCookies, loginRequestUri: new Uri(url, "/_layouts/15/settings.aspx"));

                // Ensure the login process has been completed
                if (webLoginClientContext == null)
                {
                    return(null);
                }

                var context = PnPClientContext.ConvertFrom(webLoginClientContext);
                context.ExecutingWebRequest += (sender, e) =>
                {
                    e.WebRequestExecutor.WebRequest.UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version} ({System.Environment.OSVersion.VersionString})";
                };
                if (context != null)
                {
                    context.ApplicationName         = Resources.ApplicationName;
                    context.DisableReturnValueCache = true;
                    var spoConnection = new PnPConnection(context, ConnectionType.O365, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.InteractiveLogin);
                    spoConnection.ConnectionMethod = Model.ConnectionMethod.WebLogin;
                    spoConnection.AzureEnvironment = azureEnvironment;
                    return(spoConnection);
                }

                throw new Exception("Error establishing a connection, context is null");
            }
            else
            {
                return(null);
            }
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            string           password    = new System.Net.NetworkCredential(string.Empty, certificatePassword).Password;
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM, password);

            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext  = authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate, azureEnvironment);
            var context        = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            CleanupCryptoMachineKey(certificate);

            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly));
        }
        internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();


            string         appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string         configFile    = Path.Combine(appDataFolder, "SharePointPnP.PowerShell\\tokencache.dat");
            FileTokenCache cache         = new FileTokenCache(configFile);

            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache, azureEnvironment), retryCount, retryWait * 10000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADNativeApp);

            spoConnection.ConnectionMethod = Model.ConnectionMethod.AzureADNativeApplication;
            return(spoConnection);
        }
Beispiel #6
0
        public static PnPClientContext CreatePnPClientContext(int retryCount = 10, int delay = 500)
        {
            PnPClientContext context;

            if (!String.IsNullOrEmpty(AppId) && !String.IsNullOrEmpty(AppSecret))
            {
                AuthenticationManager am            = new AuthenticationManager();
                ClientContext         clientContext = null;

                if (new Uri(DevSiteUrl).DnsSafeHost.Contains("spoppe.com"))
                {
                    clientContext = am.GetAppOnlyAuthenticatedContext(DevSiteUrl, Core.Utilities.TokenHelper.GetRealmFromTargetUrl(new Uri(DevSiteUrl)), AppId, AppSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login");
                }
                else
                {
                    clientContext = am.GetAppOnlyAuthenticatedContext(DevSiteUrl, AppId, AppSecret);
                }
                context = PnPClientContext.ConvertFrom(clientContext, retryCount, delay);
            }
            else
            {
                context             = new PnPClientContext(DevSiteUrl, retryCount, delay);
                context.Credentials = Credentials;
            }

            context.RequestTimeout = Timeout.Infinite;
            return(context);
        }
        internal static SPOnlineConnection InstantiateWebloginConnection(Uri url, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var context = PnPClientContext.ConvertFrom(authManager.GetWebLoginClientContext(url.ToString()), retryCount, retryWait * 1000);

            if (context != null)
            {
                context.RetryCount      = retryCount;
                context.Delay           = retryWait * 1000;
                context.ApplicationName = Properties.Resources.ApplicationName;
                context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
                context.DisableReturnValueCache = true;
#elif SP2016
                context.DisableReturnValueCache = true;
#endif
                var connectionType = ConnectionType.OnPrem;
                if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
                {
                    connectionType = ConnectionType.O365;
                }
                if (skipAdminCheck == false)
                {
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }
                var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
                spoConnection.ConnectionMethod = Model.ConnectionMethod.WebLogin;
                return(spoConnection);
            }
            throw new Exception("Error establishing a connection, context is null");
        }
Beispiel #8
0
        internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            Core.AuthenticationManager authManager = new Core.AuthenticationManager();

            var networkCredentials = credentials.GetNetworkCredential();

            string adfsHost;
            string adfsRelyingParty;

            GetAdfsConfigurationFromTargetUri(url, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(), networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain, adfsHost, adfsRelyingParty), retryCount, retryWait * 1000);

            context.RetryCount = retryCount;
            context.Delay      = retryWait * 1000;

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;

            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Beispiel #9
0
        internal static SPOnlineConnection InstantiateWebloginConnection(Uri url, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager = new Core.AuthenticationManager();

            var context = PnPClientContext.ConvertFrom(authManager.GetWebLoginClientContext(url.ToString()), retryCount, retryWait * 1000);

            if (context != null)
            {
                context.RetryCount      = retryCount;
                context.Delay           = retryWait * 1000;
                context.ApplicationName = Properties.Resources.ApplicationName;
                context.RequestTimeout  = requestTimeout;
                var connectionType = ConnectionType.OnPrem;
                if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
                {
                    connectionType = ConnectionType.O365;
                }
                if (skipAdminCheck == false)
                {
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }

                return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
            }
            throw new Exception("Error establishing a connection, context is null");
        }
Beispiel #10
0
        private static SPOnlineConnection InitiateAzureAdAppOnlyConnectionWithCert(Uri url, string clientId, string tenant,
                                                                                   int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry,
                                                                                   bool skipAdminCheck, AzureEnvironment azureEnvironment, X509Certificate2 certificate)
        {
            var authManager   = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext =
                authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate,
                                                                  azureEnvironment);
            var context = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);

            context.RequestTimeout = requestTimeout;
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            CleanupCryptoMachineKey(certificate);

            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null,
                                                       url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly);

            spoConnection.ConnectionMethod = ConnectionMethod.AzureADAppOnly;
            return(spoConnection);
        }
Beispiel #11
0
        //internal static Uri RedirectUri;
        //internal static string ClientId;

        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            Core.AuthenticationManager authManager = new Core.AuthenticationManager();
            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;

            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Beispiel #12
0
        internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            Core.AuthenticationManager authManager = new Core.AuthenticationManager();


            string         appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string         configFile    = Path.Combine(appDataFolder, "OfficeDevPnP.PowerShell\\tokencache.dat");
            FileTokenCache cache         = new FileTokenCache(configFile);

            var context = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache), retryCount, retryWait * 10000);

            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Beispiel #13
0
        internal static PnPConnection CreateWithWeblogin(Uri url, string tenantAdminUrl, bool clearCookies, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (Utilities.OperatingSystem.IsWindows())
            {
                // Log in to a specific page on the tenant which is known to be performant
                var webLoginClientContext = BrowserHelper.GetWebLoginClientContext(url.ToString(), clearCookies, loginRequestUri: new Uri(url, "/_layouts/15/settings.aspx"));

                // Ensure the login process has been completed
                if (webLoginClientContext == null)
                {
                    return(null);
                }

                var context = PnPClientContext.ConvertFrom(webLoginClientContext);

                if (context != null)
                {
                    context.ApplicationName         = Resources.ApplicationName;
                    context.DisableReturnValueCache = true;
                    var spoConnection = new PnPConnection(context, ConnectionType.O365, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.InteractiveLogin);
                    spoConnection.ConnectionMethod = Model.ConnectionMethod.WebLogin;
                    spoConnection.AzureEnvironment = azureEnvironment;
                    return(spoConnection);
                }

                throw new Exception("Error establishing a connection, context is null");
            }
            else
            {
                return(null);
            }
        }
Beispiel #14
0
        internal static PnPConnection CreateWithACSAppOnly(Uri url, string realm, string clientId, string clientSecret, string tenantAdminUrl, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            ConnectionType   connectionType;
            PnPClientContext context = null;

            if (url != null)
            {
                PnP.Framework.AuthenticationManager authManager = null;
                if (PnPConnection.CachedAuthenticationManager != null)
                {
                    authManager = PnPConnection.CachedAuthenticationManager;
                    PnPConnection.CachedAuthenticationManager = null;
                }
                else
                {
                    authManager = new PnP.Framework.AuthenticationManager();
                }
                using (authManager)
                {
                    if (realm == null)
                    {
                        realm = GetRealmFromTargetUrl(url);
                    }

                    if (url.DnsSafeHost.Contains("spoppe.com"))
                    {
                        context = PnPClientContext.ConvertFrom(authManager.GetACSAppOnlyContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"));
                    }
                    else
                    {
                        context = PnPClientContext.ConvertFrom(authManager.GetACSAppOnlyContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: Framework.AuthenticationManager.GetACSEndPoint(azureEnvironment), globalEndPointPrefix: Framework.AuthenticationManager.GetACSEndPointPrefix(azureEnvironment)));
                    }
                    context.ApplicationName         = Resources.ApplicationName;
                    context.DisableReturnValueCache = true;
                    connectionType = ConnectionType.O365;
                    context.ExecutingWebRequest += (sender, e) =>
                    {
                        e.WebRequestExecutor.WebRequest.UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version} ({System.Environment.OSVersion.VersionString})";
                    };
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }
            }
            else
            {
                connectionType = ConnectionType.O365;
            }

            var spoConnection = new PnPConnection(context, connectionType, null, clientId, clientSecret, url?.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.ClientIDSecret)
            {
                Tenant           = realm,
                AzureEnvironment = azureEnvironment
            };

            return(spoConnection);
        }
Beispiel #15
0
        internal static PnPConnection CreateWithACSAppOnly(Uri url, string realm, string clientId, string clientSecret, string tenantAdminUrl, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            ConnectionType   connectionType;
            PnPClientContext context = null;

            if (url != null)
            {
                PnP.Framework.AuthenticationManager authManager = null;
                if (PnPConnection.CachedAuthenticationManager != null)
                {
                    authManager = PnPConnection.CachedAuthenticationManager;
                    PnPConnection.CachedAuthenticationManager = null;
                }
                else
                {
                    authManager = new PnP.Framework.AuthenticationManager();
                }
                using (authManager)
                {
                    if (realm == null)
                    {
                        realm = GetRealmFromTargetUrl(url);
                    }

                    if (url.DnsSafeHost.Contains("spoppe.com"))
                    {
                        context = PnPClientContext.ConvertFrom(authManager.GetACSAppOnlyContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"));
                    }
                    else
                    {
                        context = PnPClientContext.ConvertFrom(authManager.GetACSAppOnlyContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: Framework.AuthenticationManager.GetACSEndPoint(azureEnvironment), globalEndPointPrefix: Framework.AuthenticationManager.GetACSEndPointPrefix(azureEnvironment)));
                    }
                    context.ApplicationName         = Resources.ApplicationName;
                    context.DisableReturnValueCache = true;
                    connectionType = ConnectionType.O365;
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }
            }
            else
            {
                connectionType = ConnectionType.O365;
            }

            var spoConnection = new PnPConnection(context, connectionType, null, clientId, clientSecret, url?.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.ClientIDSecret)
            {
                Tenant           = realm,
                AzureEnvironment = azureEnvironment
            };

            return(spoConnection);
        }
        public void TestPnPClientContextCast()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var context = PnPClientContext.ConvertFrom(clientContext);

                var lists = context.Web.Lists;
                context.Load(lists);
                context.ExecuteQueryRetry();
            }
        }
        internal static PnPConnection InstantiateDeviceLoginConnection(string url, bool launchBrowser, CmdletMessageWriter messageWriter, AzureEnvironment azureEnvironment, CancellationToken cancellationToken)
        {
            var connectionUri = new Uri(url);
            var scopes        = new[] { $"{connectionUri.Scheme}://{connectionUri.Authority}//.default" }; // the second double slash is not a typo.

            PnP.Framework.AuthenticationManager authManager = null;
            if (PnPConnection.CachedAuthenticationManager != null)
            {
                authManager = PnPConnection.CachedAuthenticationManager;
                PnPConnection.CachedAuthenticationManager = null;
            }
            else
            {
                Func <DeviceCodeResult, Task> deviceCodeCallback = (deviceCodeResult) =>
                {
                    if (launchBrowser)
                    {
                        if (Utilities.OperatingSystem.IsWindows())
                        {
                            ClipboardService.SetText(deviceCodeResult.UserCode);
                            messageWriter.WriteMessage($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard\n\n");
                            BrowserHelper.GetWebBrowserPopup(deviceCodeResult.VerificationUrl, "Please log in");
                        }
                        else
                        {
                            messageWriter.WriteMessage($"\n\n{deviceCodeResult.Message}\n\n");
                        }
                    }
                    else
                    {
                        messageWriter.WriteMessage($"\n\n{deviceCodeResult.Message}\n\n");
                    }
                    return(Task.FromResult(0));
                };

                authManager = new PnP.Framework.AuthenticationManager(PnPConnection.PnPManagementShellClientId, deviceCodeCallback, azureEnvironment);
            }
            using (authManager)
            {
                var clientContext = authManager.GetContext(url.ToString(), cancellationToken);
                var context       = PnPClientContext.ConvertFrom(clientContext);

                var connectionType = ConnectionType.O365;

                var spoConnection = new PnPConnection(context, connectionType, null, PnPConnection.PnPManagementShellClientId, null, url.ToString(), null, PnPPSVersionTag, InitializationType.DeviceLogin)
                {
                    ConnectionMethod = ConnectionMethod.DeviceLogin,
                    AzureEnvironment = azureEnvironment
                };
                return(spoConnection);
            }
        }
Beispiel #18
0
        internal static PnPConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, string tenantAdminUrl, bool disableTelemetry, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var context = new PnPClientContext(url.AbsoluteUri)
            {
                ApplicationName         = Resources.ApplicationName,
                DisableReturnValueCache = true
            };
            var tenantId = string.Empty;

            try
            {
                using (var authManager = new PnP.Framework.AuthenticationManager(credentials.UserName, credentials.Password))
                {
                    context = PnPClientContext.ConvertFrom(authManager.GetContext(url.ToString()));
                    context.ExecuteQueryRetry();

                    var accessToken = authManager.GetAccessTokenAsync(url.ToString()).GetAwaiter().GetResult();
                    var parsedToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
                    tenantId = parsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value;
                }
            }
            catch (ClientRequestException)
            {
                context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
            }
            catch (ServerException)
            {
                context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
            }
            var connectionType = ConnectionType.O365;

            if (url.Host.ToLowerInvariant().EndsWith($"sharepoint.{PnP.Framework.AuthenticationManager.GetSharePointDomainSuffix(azureEnvironment)}"))
            {
                connectionType = ConnectionType.O365;
            }

            if (IsTenantAdminSite(context))
            {
                connectionType = ConnectionType.TenantAdmin;
            }
            var spoConnection = new PnPConnection(context, connectionType, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, disableTelemetry, InitializationType.Credentials)
            {
                ConnectionMethod = Model.ConnectionMethod.Credentials,
                AzureEnvironment = azureEnvironment,
                Tenant           = tenantId
            };

            return(spoConnection);
        }
        internal static SPOnlineConnection InitiateAccessTokenConnection(Uri url, string accessToken, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAccessTokenAuthenticatedContext(url.ToString(), accessToken), retryCount, retryWait);
            var connectionType = ConnectionType.O365;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
Beispiel #20
0
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            Core.AuthenticationManager authManager = new Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword), retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Beispiel #21
0
        public static PnPClientContext CreatePnPClientContext(int retryCount = 10, int delay = 500)
        {
            PnPClientContext context;

            if (!String.IsNullOrEmpty(AppId) && !String.IsNullOrEmpty(AppSecret))
            {
                AuthenticationManager am = new AuthenticationManager();
                var clientContext        = am.GetAppOnlyAuthenticatedContext(DevSiteUrl, AppId, AppSecret);
                context = PnPClientContext.ConvertFrom(clientContext, retryCount, delay);
            }
            else
            {
                context             = new PnPClientContext(DevSiteUrl, retryCount, delay);
                context.Credentials = Credentials;
            }

            context.RequestTimeout = Timeout.Infinite;
            return(context);
        }
Beispiel #22
0
        internal static PnPConnection CreateWithInteractiveLogin(Uri uri, string clientId, string tenantAdminUrl, bool launchBrowser, AzureEnvironment azureEnvironment, CancellationTokenSource cancellationTokenSource, bool forceAuthentication, string tenant)
        {
            PnP.Framework.AuthenticationManager authManager = null;
            if (PnPConnection.CachedAuthenticationManager != null && !forceAuthentication)
            {
                authManager = PnPConnection.CachedAuthenticationManager;
                PnPConnection.CachedAuthenticationManager = null;
            }
            else
            {
                authManager = PnP.Framework.AuthenticationManager.CreateWithInteractiveLogin(clientId, (url, port) =>
                {
                    BrowserHelper.OpenBrowserForInteractiveLogin(url, port, !launchBrowser, cancellationTokenSource);
                },
                                                                                             tenant,
                                                                                             successMessageHtml: $"You successfully authenticated with PnP PowerShell. Feel free to close this {(launchBrowser ? "tab" : "window")}.",
                                                                                             failureMessageHtml: $"You did not authenticate with PnP PowerShell. Feel free to close this browser {(launchBrowser ? "tab" : "window")}.",
                                                                                             azureEnvironment: azureEnvironment);
            }
            using (authManager)
            {
                var clientContext = authManager.GetContext(uri.ToString(), cancellationTokenSource.Token);
                var context       = PnPClientContext.ConvertFrom(clientContext);
                context.ExecutingWebRequest += (sender, e) =>
                {
                    e.WebRequestExecutor.WebRequest.UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version} ({System.Environment.OSVersion.VersionString})";
                };
                var connectionType = ConnectionType.O365;

                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }

                var spoConnection = new PnPConnection(context, connectionType, null, clientId, null, uri.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.ClientIDCertificate)
                {
                    ConnectionMethod = ConnectionMethod.Credentials,
                    AzureEnvironment = azureEnvironment
                };
                return(spoConnection);
            }
        }
        internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var networkCredentials = credentials.GetNetworkCredential();

            string adfsHost;
            string adfsRelyingParty;

            GetAdfsConfigurationFromTargetUri(url, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(), networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain, adfsHost, adfsRelyingParty), retryCount, retryWait * 1000);

            context.RetryCount = retryCount;
            context.Delay      = retryWait * 1000;

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif

            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.ADFS;
            return(spoConnection);
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            PnPClientContext context;

            if (url.DnsSafeHost.Contains("spoppe.com"))
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"), retryCount, retryWait * 1000);
            }
            else
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000);
            }

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
Beispiel #25
0
        internal static PnPConnection CreateWithAccessToken(Uri url, string accessToken, string tenantAdminUrl)
        {
            using (var authManager = new PnP.Framework.AuthenticationManager(new System.Net.NetworkCredential("", accessToken).SecurePassword))
            {
                PnPClientContext context        = null;
                ConnectionType   connectionType = ConnectionType.O365;
                if (url != null)
                {
                    context = PnPClientContext.ConvertFrom(authManager.GetContext(url.ToString()));
                    context.ApplicationName         = Resources.ApplicationName;
                    context.DisableReturnValueCache = true;
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }

                var connection = new PnPConnection(context, connectionType, null, url != null ? url.ToString() : null, tenantAdminUrl, PnPPSVersionTag, InitializationType.Token);
                return(connection);
            }
        }
Beispiel #26
0
        internal static PnPConnection CreateWithCert(Uri url, string clientId, string tenant, string tenantAdminUrl, AzureEnvironment azureEnvironment, X509Certificate2 certificate, bool certificateFromFile = false)
        {
            PnP.Framework.AuthenticationManager authManager = null;
            if (PnPConnection.CachedAuthenticationManager != null)
            {
                authManager = PnPConnection.CachedAuthenticationManager;
                PnPConnection.CachedAuthenticationManager = null;
            }
            else
            {
                authManager = PnP.Framework.AuthenticationManager.CreateWithCertificate(clientId, certificate, tenant, azureEnvironment: azureEnvironment);
            }
            using (authManager)
            {
                var clientContext = authManager.GetContext(url.ToString());
                var context       = PnPClientContext.ConvertFrom(clientContext);
                context.ExecutingWebRequest += (sender, e) =>
                {
                    e.WebRequestExecutor.WebRequest.UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version} ({System.Environment.OSVersion.VersionString})";
                };

                var connectionType = ConnectionType.O365;

                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }

                var spoConnection = new PnPConnection(context, connectionType, null, clientId, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.ClientIDCertificate)
                {
                    ConnectionMethod = ConnectionMethod.AzureADAppOnly,
                    Certificate      = certificate,
                    Tenant           = tenant,
                    DeleteCertificateFromCacheOnDisconnect = certificateFromFile,
                    AzureEnvironment = azureEnvironment
                };
                return(spoConnection);
            }
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM);

            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext  = authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate, azureEnvironment);
            var context        = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword, azureEnvironment), retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);

            spoConnection.ConnectionMethod = Model.ConnectionMethod.AzureADAppOnly;
            return(spoConnection);
        }
Beispiel #29
0
        internal static PnPConnection CreateWithInteractiveLogin(Uri uri, string clientId, string tenantAdminUrl, bool launchBrowser, AzureEnvironment azureEnvironment, CancellationTokenSource cancellationTokenSource, bool forceAuthentication, string tenant)
        {
            PnP.Framework.AuthenticationManager authManager = null;
            if (PnPConnection.CachedAuthenticationManager != null && !forceAuthentication)
            {
                authManager = PnPConnection.CachedAuthenticationManager;
                PnPConnection.CachedAuthenticationManager = null;
            }
            else
            {
                authManager = PnP.Framework.AuthenticationManager.CreateWithInteractiveLogin(clientId, (url, port) =>
                {
                    BrowserHelper.OpenBrowserForInteractiveLogin(url, port, !launchBrowser, cancellationTokenSource);
                },
                                                                                             tenant,
                                                                                             successMessageHtml: $"You successfully authenticated with PnP PowerShell. Feel free to close this {(launchBrowser ? "tab" : "window")}.",
                                                                                             failureMessageHtml: $"You did not authenticate with PnP PowerShell. Feel free to close this browser {(launchBrowser ? "tab" : "window")}.",
                                                                                             azureEnvironment: azureEnvironment);
            }
            using (authManager)
            {
                var clientContext = authManager.GetContext(uri.ToString(), cancellationTokenSource.Token);
                var context       = PnPClientContext.ConvertFrom(clientContext);

                var connectionType = ConnectionType.O365;

                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }

                var spoConnection = new PnPConnection(context, connectionType, null, clientId, null, uri.ToString(), tenantAdminUrl, PnPPSVersionTag, InitializationType.ClientIDCertificate)
                {
                    ConnectionMethod = ConnectionMethod.Credentials,
                    AzureEnvironment = azureEnvironment
                };
                return(spoConnection);
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Admin, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            dynamic data = await req.Content.ReadAsAsync <object>();

            string SPParentSiteUrl   = data["SPParentSiteUrl"];
            string SPWebTemplate     = data["SPWebTemplate"];
            string SPSiteTitle       = data["SPSiteTitle"];
            string SPSiteDescription = data["SPSiteDescription"];
            string SPSiteURL         = data["SPSiteURL"];
            int    SPSiteLanguage    = data["SPSiteLanguage"];

            log.Info($"SPParentSiteUrl = '{SPParentSiteUrl}'");
            log.Info($"SPWebTemplate = '{SPWebTemplate}'");
            log.Info($"SPSiteTitle = '{SPSiteTitle}'");
            log.Info($"SPSiteDescription = '{SPSiteDescription}'");
            log.Info($"SPSiteURL = '{SPSiteURL}'");
            log.Info($"SPSiteLanguage = '{SPSiteLanguage}'");

            string userName = System.Environment.GetEnvironmentVariable("SPUser", EnvironmentVariableTarget.Process);
            string password = System.Environment.GetEnvironmentVariable("SPPwd", EnvironmentVariableTarget.Process);

            var authenticationManager = new PnPAuthenticationManager();
            var clientContext         = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(SPParentSiteUrl, userName, password);
            var pnpClientContext      = PnPClientContext.ConvertFrom(clientContext);

            var webCreationInfo = new Microsoft.SharePoint.Client.WebCreationInformation();

            webCreationInfo.WebTemplate = SPWebTemplate;
            webCreationInfo.Title       = SPSiteTitle;
            webCreationInfo.Description = SPSiteDescription;
            webCreationInfo.Url         = SPSiteURL;
            webCreationInfo.Language    = SPSiteLanguage;

            pnpClientContext.Web.Webs.Add(webCreationInfo);
            pnpClientContext.ExecuteQuery();

            return(req.CreateResponse(HttpStatusCode.OK, "request done"));
        }