Exemple #1
0
        /// <summary>
        /// Returns a PnPConnection based on connecting using an existing token
        /// </summary>
        /// <param name="token">Token to connect with</param>
        /// <param name="tokenAudience">Indicator of <see cref="TokenAudience"/> indicating for which API this token is meant to be used</param>
        /// <param name="host">PowerShell Host environment in which the commands are being run</param>
        /// <param name="initializationType">Indicator of type <see cref="InitializationType"/> which indicates the method used to set up the connection. Used for gathering usage analytics.</param>
        /// <param name="url">Url of the SharePoint environment to connect to, if applicable. Leave NULL not to connect to a SharePoint environment.</param>
        /// <param name="clientContext">A SharePoint ClientContext to make available within this connection. Leave NULL to not connect to a SharePoint environment.</param>
        /// <param name="minimalHealthScore">Minimum health score that the SharePoint server should report before allowing requests to be executed on it. Scale of 0 to 10 where 0 is healthiest and 10 is least healthy. Leave NULL not to perform health checks on SharePoint.</param>
        /// <param name="pnpVersionTag">Identifier set on the SharePoint ClientContext as the ClientTag to identify the source of the requests to SharePoint. Leave NULL not to set it.</param>
        /// <param name="disableTelemetry">Boolean indicating if telemetry on the commands being executed should be disabled. Telemetry is enabled by default.</param>
        /// <returns><see cref="PnPConnection"/ instance which can be used to communicate with one of the supported APIs</returns>
        public static PnPConnection GetConnectionWithToken(GenericToken token,
                                                           TokenAudience tokenAudience,
                                                           PSHost host,
                                                           InitializationType initializationType,
                                                           PSCredential credentials,
                                                           string url = null,
                                                           ClientContext clientContext       = null,
                                                           int?minimalHealthScore            = null,
                                                           string pnpVersionTag              = null,
                                                           bool disableTelemetry             = false,
                                                           AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var connection = new PnPConnection(host, initializationType, url, clientContext, new Dictionary <TokenAudience, GenericToken>(1)
            {
                { tokenAudience, token }
            }, minimalHealthScore, pnpVersionTag, disableTelemetry)
            {
                ConnectionMethod = ConnectionMethod.AccessToken,
                Tenant           = token.ParsedToken.Claims.FirstOrDefault(c => c.Type.Equals("tid", StringComparison.InvariantCultureIgnoreCase))?.Value,
                ClientId         = token.ParsedToken.Claims.FirstOrDefault(c => c.Type.Equals("appid", StringComparison.InvariantCultureIgnoreCase))?.Value,
                AzureEnvironment = azureEnvironment
            };

            connection.PSCredential = credentials;
            return(connection);
        }
        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);
            }
        }
Exemple #3
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);
            }
        }
        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);
            }
        }
Exemple #5
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);
            }
        }
Exemple #6
0
        /// <summary>
        /// Connect using the parameter set DEVICELOGIN
        /// </summary>
        /// <returns>PnPConnection based on the parameters provided in the parameter set</returns>
        private PnPConnection ConnectDeviceLogin(CancellationToken cancellationToken)
        {
            var           messageWriter = new CmdletMessageWriter(this);
            PnPConnection connection    = null;
            var           uri           = new Uri(Url);

            if ($"https://{uri.Host}".Equals(Url.ToLower()))
            {
                Url += "/";
            }
            var task = Task.Factory.StartNew(() =>
            {
                Uri oldUri = null;

                if (PnPConnection.CurrentConnection != null)
                {
                    if (PnPConnection.CurrentConnection.Url != null)
                    {
                        oldUri = new Uri(PnPConnection.CurrentConnection.Url);
                    }
                }
                if (oldUri != null && oldUri.Host == new Uri(Url).Host&& PnPConnection.CurrentConnection?.ConnectionMethod == ConnectionMethod.DeviceLogin)
                {
                    ReuseAuthenticationManager();
                }

                var returnedConnection = PnPConnectionHelper.InstantiateDeviceLoginConnection(Url, LaunchBrowser, messageWriter, AzureEnvironment, cancellationToken);
                connection             = returnedConnection;
                messageWriter.Finished = true;
            }, cancellationToken);

            messageWriter.Start();
            return(connection);
        }
Exemple #7
0
        internal static PnPConnection InstantiateDeviceLoginConnection(string url, bool launchBrowser, string tenantAdminUrl, PSHost host, bool disableTelemetry, AzureEnvironment azureEnvironment)
        {
            var          connectionUri = new Uri(url);
            var          scopes        = new[] { $"{connectionUri.Scheme}://{connectionUri.Authority}//.default" }; // the second double slash is not a typo.
            var          context       = new ClientContext(url);
            GenericToken tokenResult   = null;

            try
            {
                tokenResult = GraphToken.AcquireApplicationTokenDeviceLogin(PnPConnection.PnPManagementShellClientId, scopes, PnPConnection.DeviceLoginCallback(host, launchBrowser), azureEnvironment);
            }
            catch (MsalUiRequiredException ex)
            {
                if (ex.Classification == UiRequiredExceptionClassification.ConsentRequired)
                {
                    host.UI.WriteLine("You need to provide consent to the PnP Management Shell application for your tenant. The easiest way to do this is by issueing: 'Connect-PnPOnline -Url [yoursiteur] -PnPManagementShell -LaunchBrowser'. Make sure to authenticate as a Azure administrator allowing to provide consent to the application. Follow the steps provided.");
                    throw ex;
                }
            }
            var spoConnection = new PnPConnection(context, tokenResult, ConnectionType.O365, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, disableTelemetry, InitializationType.DeviceLogin)
            {
                //var spoConnection = new PnPConnection(context, ConnectionType.O365, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.DeviceLogin);
                Scopes           = scopes,
                AzureEnvironment = azureEnvironment
            };

            if (spoConnection != null)
            {
                spoConnection.ConnectionMethod = ConnectionMethod.DeviceLogin;
            }
            return(spoConnection);
        }
Exemple #8
0
        private PnPConnection ConnectManagedIdentity()
        {
            WriteVerbose("Connecting to the Graph with the current Managed Identity");
            var connection = new PnPConnection(null, InitializationType.Graph);

            return(connection);
        }
Exemple #9
0
        internal static PnPConnection CreateWithManagedIdentity(Cmdlet cmdlet, string tenantAdminUrl, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            //var httpClient = PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient();
            //var accesstoken = TokenHandler.GetManagedIdentityTokenAsync(cmdlet, httpClient, $"https://{AzureAuthHelper.GetGraphEndPoint(azureEnvironment)}/").GetAwaiter().GetResult();
            var connection = new PnPConnection(PnPPSVersionTag, InitializationType.Graph, tenantAdminUrl);

            return(connection);
        }
Exemple #10
0
        internal static PnPConnection InstantiateManagedIdentityConnection(Cmdlet cmdlet, string tenantAdminUrl)
        {
            var httpClient  = PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient();
            var accesstoken = TokenHandler.GetManagedIdentityTokenAsync(cmdlet, httpClient, "https://graph.microsoft.com/").GetAwaiter().GetResult();
            var connection  = new PnPConnection(PnPPSVersionTag, InitializationType.Graph, tenantAdminUrl);

            return(connection);
        }
        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);
        }
Exemple #12
0
        internal static PnPConnection InstantiateGraphAccessTokenConnection(string accessToken, bool disableTelemetry)
        {
            var tokenResult   = new GenericToken(accessToken);
            var spoConnection = new PnPConnection(tokenResult, ConnectionMethod.AccessToken, ConnectionType.O365, PnPPSVersionTag, disableTelemetry, InitializationType.Graph)
            {
                ConnectionMethod = ConnectionMethod.GraphDeviceLogin
            };

            return(spoConnection);
        }
Exemple #13
0
        internal static PnPConnection InstantiateGraphDeviceLoginConnection(bool launchBrowser, PSHost host, bool disableTelemetry, AzureEnvironment azureEnvironment)
        {
            var tokenResult   = GraphToken.AcquireApplicationTokenDeviceLogin(PnPConnection.PnPManagementShellClientId, new[] { "Group.Read.All", "openid", "email", "profile", "Group.ReadWrite.All", "User.Read.All", "Directory.ReadWrite.All" }, PnPConnection.DeviceLoginCallback(host, launchBrowser), azureEnvironment);
            var spoConnection = new PnPConnection(tokenResult, ConnectionMethod.GraphDeviceLogin, ConnectionType.O365, PnPPSVersionTag, disableTelemetry, InitializationType.GraphDeviceLogin)
            {
                Scopes           = new[] { "Group.Read.All", "openid", "email", "profile", "Group.ReadWrite.All", "User.Read.All", "Directory.ReadWrite.All" },
                AzureEnvironment = azureEnvironment
            };

            return(spoConnection);
        }
Exemple #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;
                    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);
        }
 internal static bool DisconnectProvidedService(PnPConnection connection)
 {
     Environment.SetEnvironmentVariable("PNPPSHOST", string.Empty);
     Environment.SetEnvironmentVariable("PNPPSSITE", string.Empty);
     if (connection == null)
     {
         return(false);
     }
     connection.Context = null;
     connection         = null;
     return(true);
 }
Exemple #16
0
 private PnPConnection ConnectWebLogin()
 {
     WriteWarning("Consider using -Interactive instead, which provides better functionality. See the documentation at https://pnp.github.io/powershell/cmdlets/Connect-PnPOnline.html#interactive-login-for-multi-factor-authentication");
     if (Utilities.OperatingSystem.IsWindows())
     {
         return(PnPConnection.CreateWithWeblogin(new Uri(Url.ToLower()), TenantAdminUrl, ForceAuthentication));
     }
     else
     {
         throw new PSArgumentException("-UseWebLogin only works when running on Microsoft Windows due to the requirement to show a login window.");
     }
 }
        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);
            }
        }
Exemple #18
0
 /// <summary>
 /// Connect using the paramater set TOKEN
 /// </summary>
 /// <returns>PnPConnection based on the parameters provided in the parameter set</returns>
 private PnPConnection ConnectACSAppOnly()
 {
     CmdletMessageWriter.WriteFormattedMessage(this, new CmdletMessageWriter.Message {
         Text = "Connecting with Client Secret uses legacy authentication and provides limited functionality. We can for instance not execute requests towards the Microsoft Graph, which limits cmdlets related to Microsoft Teams, Microsoft Planner, Microsoft Flow and Microsoft 365 Groups. You can hide this warning by using Connect-PnPOnline [your parameters] -WarningAction Ignore", Formatted = true, Type = CmdletMessageWriter.MessageType.Warning
     });
     if (PnPConnection.Current?.ClientId == ClientId &&
         PnPConnection.Current?.ClientSecret == ClientSecret &&
         PnPConnection.Current?.Tenant == Realm)
     {
         ReuseAuthenticationManager();
     }
     return(PnPConnection.CreateWithACSAppOnly(new Uri(Url), Realm, ClientId, ClientSecret, TenantAdminUrl, AzureEnvironment));
 }
Exemple #19
0
        protected override void ProcessRecord()
        {
            // If no specific connection has been passed in, take the connection from the current context
            if (Connection == null)
            {
                Connection = PnPConnection.CurrentConnection;
            }
#if !ONPREMISES
            if (Connection?.Certificate != null)
            {
#if !PNPPSCORE
                if (Connection != null && Connection.DeleteCertificateFromCacheOnDisconnect)
                {
                    PnPConnectionHelper.CleanupCryptoMachineKey(Connection.Certificate);
                }
#endif
                Connection.Certificate = null;
            }
#endif
            var success = false;
            if (Connection != null)
            {
                success = DisconnectProvidedService(Connection);
            }
            else
            {
                success = DisconnectCurrentService();
            }
            if (!success)
            {
                throw new InvalidOperationException(Properties.Resources.NoConnectionToDisconnect);
            }

            // clear credentials
            PnPConnection.CurrentConnection = null;

            var provider = SessionState.Provider.GetAll().FirstOrDefault(p => p.Name.Equals(SPOProvider.PSProviderName, StringComparison.InvariantCultureIgnoreCase));
            if (provider != null)
            {
                //ImplementingAssembly was introduced in Windows PowerShell 5.0.
#if !PNPPSCORE
                var drives = Host.Version.Major >= 5 ? provider.Drives.Where(d => d.Provider.Module.ImplementingAssembly.FullName == Assembly.GetExecutingAssembly().FullName) : provider.Drives;
#else
                var drives = Host.Version.Major >= 5 ? provider.Drives.Where(d => d.Provider.Module.Name == Assembly.GetExecutingAssembly().FullName) : provider.Drives;
#endif
                foreach (var drive in drives)
                {
                    SessionState.Drive.Remove(drive.Name, true, "Global");
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Connect using the parameter set DEVICELOGIN
        /// </summary>
        /// <returns>PnPConnection based on the parameters provided in the parameter set</returns>
        private PnPConnection ConnectDeviceLogin()
        {
            var           messageWriter = new CmdletMessageWriter(this);
            PnPConnection connection    = null;
            var           uri           = new Uri(Url);

            if ($"https://{uri.Host}".Equals(Url.ToLower()))
            {
                Url += "/";
            }
            var task = Task.Factory.StartNew(() =>
            {
                try
                {
                    Uri oldUri = null;

                    if (PnPConnection.Current != null)
                    {
                        if (PnPConnection.Current.Url != null)
                        {
                            oldUri = new Uri(PnPConnection.Current.Url);
                        }
                    }
                    if (oldUri != null && oldUri.Host == new Uri(Url).Host&& PnPConnection.Current?.ConnectionMethod == ConnectionMethod.DeviceLogin)
                    {
                        ReuseAuthenticationManager();
                    }

                    var clientId = PnPConnection.PnPManagementShellClientId;
                    if (ParameterSpecified(nameof(ClientId)))
                    {
                        clientId = ClientId;
                    }


                    var returnedConnection = PnPConnection.CreateWithDeviceLogin(clientId, Url, Tenant, LaunchBrowser, messageWriter, AzureEnvironment, cancellationTokenSource);
                    connection             = returnedConnection;
                    messageWriter.Finished = true;
                }
                catch (Exception ex)
                {
                    messageWriter.WriteWarning(ex.Message, false);
                    messageWriter.Finished = true;
                }
            }, cancellationTokenSource.Token);

            messageWriter.Start();
            return(connection);
        }
Exemple #21
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);
        }
Exemple #22
0
 private PnPConnection ConnectInteractive()
 {
     if (ClientId == null)
     {
         ClientId = PnPConnection.PnPManagementShellClientId;
     }
     if (PnPConnection.Current?.ClientId == ClientId)
     {
         if (IsSameOrAdminHost(new Uri(Url), new Uri(PnPConnection.Current.Url)))
         {
             ReuseAuthenticationManager();
         }
     }
     return(PnPConnection.CreateWithInteractiveLogin(new Uri(Url.ToLower()), ClientId, TenantAdminUrl, LaunchBrowser, AzureEnvironment, cancellationTokenSource, ForceAuthentication, Tenant));
 }
Exemple #23
0
 internal static bool DisconnectProvidedService(PnPConnection connection)
 {
     //connection.ClearTokens();
     Environment.SetEnvironmentVariable("PNPPSHOST", string.Empty);
     Environment.SetEnvironmentVariable("PNPPSSITE", string.Empty);
     if (connection == null)
     {
         return(false);
     }
     //GraphToken.ClearCaches();
     //OfficeManagementApiToken.ClearCaches();
     GenericToken.ClearCaches();
     connection.Context = null;
     connection         = null;
     return(true);
 }
        /// <summary>
        /// Connect using the parameter set ACCESSTOKEN
        /// </summary>
        /// <returns>PnPConnection based on the parameters provided in the parameter set</returns>
        private PnPConnection ConnectAccessToken()
        {
            var handler  = new JwtSecurityTokenHandler();
            var jwtToken = handler.ReadJwtToken(AccessToken);
            var aud      = jwtToken.Audiences.FirstOrDefault();
            var url      = Url ?? aud ?? throw new PSArgumentException(Resources.AccessTokenConnectFailed);

            switch (url.ToLower())
            {
            case GraphToken.ResourceIdentifier:
                return(PnPConnection.GetConnectionWithToken(new GraphToken(AccessToken), TokenAudience.MicrosoftGraph, InitializationType.Token, null, disableTelemetry: NoTelemetry.ToBool()));

            case OfficeManagementApiToken.ResourceIdentifier:
                return(PnPConnection.GetConnectionWithToken(new OfficeManagementApiToken(AccessToken), TokenAudience.OfficeManagementApi, InitializationType.Token, null, disableTelemetry: NoTelemetry.ToBool()));

            default:
                return(PnPConnection.GetConnectionWithToken(new SharePointToken(AccessToken), TokenAudience.SharePointOnline, InitializationType.Token, null, Url, disableTelemetry: NoTelemetry.ToBool()));
            }
        }
        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);
            }
        }
Exemple #26
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);
            }
        }
        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);
            }
        }
Exemple #28
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);
            }
        }
Exemple #29
0
        /// <summary>
        /// Connect using provided credentials or the current credentials
        /// </summary>
        /// <returns>PnPConnection based on credentials authentication</returns>
        private PnPConnection ConnectCredentials(PSCredential credentials, InitializationType initializationType = InitializationType.Credentials)
        {
            if (!CurrentCredentials && credentials == null)
            {
                credentials = GetCredentials();
                if (credentials == null)
                {
                    credentials = Host.UI.PromptForCredential(Resources.EnterYourCredentials, "", "", "");

                    // Ensure credentials have been entered
                    if (credentials == null)
                    {
                        // No credentials have been provided
                        return(null);
                    }
                }
            }
            if (ClientId == null)
            {
                ClientId = PnPConnection.PnPManagementShellClientId;
            }

            if (PnPConnection.Current?.ClientId == ClientId)
            {
                if (credentials != null && PnPConnection.Current?.PSCredential?.UserName == credentials.UserName &&
                    PnPConnection.Current?.PSCredential.GetNetworkCredential().Password == credentials.GetNetworkCredential().Password)
                {
                    ReuseAuthenticationManager();
                }
            }

            return(PnPConnection.CreateWithCredentials(this, new Uri(Url),
                                                       credentials,
                                                       CurrentCredentials,
                                                       TenantAdminUrl,
                                                       AzureEnvironment,
                                                       ClientId,
                                                       RedirectUri, TransformationOnPrem, initializationType));
        }
        /// <summary>
        /// Connect using the parameter set AADWITHSCOPE
        /// </summary>
        /// <param name="credentials">Credentials to authenticate with for delegated access or NULL for application permissions</param>
        /// <returns>PnPConnection based on the parameters provided in the parameter set</returns>
        private PnPConnection ConnectAadWithScope(PSCredential credentials, AzureEnvironment azureEnvironment)
        {
            // Filter out the scopes for the Microsoft Office 365 Management API
            var officeManagementApiScopes = Enum.GetNames(typeof(OfficeManagementApiPermission)).Select(s => s.Replace("_", ".")).Intersect(Scopes).ToArray();

            // Take the remaining scopes and try requesting them from the Microsoft Graph API
            var graphScopes = Scopes.Except(officeManagementApiScopes).ToArray();

            PnPConnection connection = null;

            // If we have Office 365 scopes, get a token for those first
            if (officeManagementApiScopes.Length > 0)
            {
                var officeManagementApiToken = credentials == null?OfficeManagementApiToken.AcquireApplicationTokenDeviceLogin(PnPConnection.PnPManagementShellClientId, officeManagementApiScopes, PnPConnection.DeviceLoginCallback(this.Host, true), azureEnvironment) : OfficeManagementApiToken.AcquireDelegatedTokenWithCredentials(PnPConnection.PnPManagementShellClientId, officeManagementApiScopes, credentials.UserName, credentials.Password);

                connection = PnPConnection.GetConnectionWithToken(officeManagementApiToken, TokenAudience.OfficeManagementApi, InitializationType.InteractiveLogin, credentials, disableTelemetry: NoTelemetry.ToBool());
            }

            // If we have Graph scopes, get a token for it
            if (graphScopes.Length > 0)
            {
                var graphToken = credentials == null?GraphToken.AcquireApplicationTokenDeviceLogin(PnPConnection.PnPManagementShellClientId, graphScopes, PnPConnection.DeviceLoginCallback(this.Host, true), azureEnvironment) : GraphToken.AcquireDelegatedTokenWithCredentials(PnPConnection.PnPManagementShellClientId, graphScopes, credentials.UserName, credentials.Password, AzureEnvironment);

                // If there's a connection already, add the AAD token to it, otherwise set up a new connection with it
                if (connection != null)
                {
                    //connection.AddToken(TokenAudience.MicrosoftGraph, graphToken);
                }
                else
                {
                    connection = PnPConnection.GetConnectionWithToken(graphToken, TokenAudience.MicrosoftGraph, InitializationType.InteractiveLogin, credentials, disableTelemetry: NoTelemetry.ToBool());
                }
            }
            connection.Scopes = Scopes;
            return(connection);
        }