/// <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); }
/// <summary> /// Connect using the paramater set TOKEN /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectACSAppOnly() { if (PnPConnection.CurrentConnection?.ClientId == ClientId && PnPConnection.CurrentConnection?.ClientSecret == ClientSecret && PnPConnection.CurrentConnection?.Tenant == AADDomain) { ReuseAuthenticationManager(); } return(PnPConnectionHelper.InstantiateACSAppOnlyConnection(new Uri(Url), AADDomain, ClientId, ClientSecret, TenantAdminUrl, AzureEnvironment)); }
private PnPConnection ConnectWebLogin() { if (Utilities.OperatingSystem.IsWindows()) { return(PnPConnectionHelper.InstantiateWebloginConnection(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."); } }
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(PnPConnectionHelper.InstantiateWebloginConnection(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."); } }
/// <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.CurrentConnection?.ClientId == ClientId && PnPConnection.CurrentConnection?.ClientSecret == ClientSecret && PnPConnection.CurrentConnection?.Tenant == AADDomain) { ReuseAuthenticationManager(); } return(PnPConnectionHelper.InstantiateACSAppOnlyConnection(new Uri(Url), AADDomain, ClientId, ClientSecret, TenantAdminUrl, AzureEnvironment)); }
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"); } } }
private PnPConnection ConnectInteractive() { if (ClientId == null) { ClientId = PnPConnection.PnPManagementShellClientId; } if (PnPConnection.CurrentConnection?.ClientId == ClientId) { if (IsSameOrAdminHost(new Uri(Url), new Uri(PnPConnection.CurrentConnection.Url))) { ReuseAuthenticationManager(); } // if (new Uri(Url.ToLower()).Host == new Uri(PnPConnection.CurrentConnection.Url).Host ) // { // ReuseAuthenticationManager(); // } } return(PnPConnectionHelper.InstantiateInteractiveConnection(new Uri(Url.ToLower()), ClientId, TenantAdminUrl, LaunchBrowser, AzureEnvironment, cancellationTokenSource, ForceAuthentication)); }
/// <summary> /// Connect using the parameter set APPONLYAAD /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectAppOnlyAad() { if (ParameterSpecified(nameof(CertificatePath))) { //WriteWarning(@"Your certificate is copied by the operating system to c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys. Over time this folder may increase heavily in size. Use Disconnect-PnPOnline in your scripts remove the certificate from this folder to clean up. Consider using -Thumbprint instead of -CertificatePath."); return(PnPConnectionHelper.InitiateAzureADAppOnlyConnection(new Uri(Url), ClientId, Tenant, CertificatePath, CertificatePassword, TenantAdminUrl, NoTelemetry, AzureEnvironment)); } else if (ParameterSpecified(nameof(Certificate))) { return(PnPConnectionHelper.InitiateAzureAdAppOnlyConnectionWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, NoTelemetry, AzureEnvironment, Certificate)); } else if (ParameterSpecified(nameof(CertificateBase64Encoded))) { return(PnPConnectionHelper.InitiateAzureAdAppOnlyConnectionWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, NoTelemetry, AzureEnvironment, CertificateBase64Encoded)); } else { throw new ArgumentException("You must either provide CertificatePath, Certificate or CertificateBase64Encoded when connecting using an Azure Active Directory registered application"); } }
/// <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.CurrentConnection?.ClientId == ClientId) { if (credentials != null && PnPConnection.CurrentConnection?.PSCredential?.UserName == credentials.UserName && PnPConnection.CurrentConnection?.PSCredential.GetNetworkCredential().Password == credentials.GetNetworkCredential().Password) { ReuseAuthenticationManager(); } } return(PnPConnectionHelper.InstantiateConnectionWithCredentials(this, new Uri(Url), credentials, CurrentCredentials, TenantAdminUrl, AzureEnvironment, ClientId, RedirectUri, TransformationOnPrem, initializationType)); }
/// <summary> /// Connect using the parameter set SPOMANAGEMENT /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> //private PnPConnection ConnectSpoManagement() //{ // return ConnectNativeAAD(SPOManagementClientId, SPOManagementRedirectUri); //} /// <summary> /// Connect using the parameter set DEVICELOGIN /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectDeviceLogin() { bool ctrlCAsInput = false; if (Host.Name == "ConsoleHost") { ctrlCAsInput = Console.TreatControlCAsInput; Console.TreatControlCAsInput = true; } var uri = new Uri(Url); if ($"https://{uri.Host}".Equals(Url.ToLower())) { Url += "/"; } var connection = PnPConnectionHelper.InstantiateDeviceLoginConnection(Url, LaunchBrowser, TenantAdminUrl, Host, NoTelemetry, AzureEnvironment); if (Host.Name == "ConsoleHost") { Console.TreatControlCAsInput = ctrlCAsInput; } return(connection); }
/// <summary> /// Connect using the parameter set GRAPHDEVICELOGIN /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectGraphDeviceLogin(string accessToken) { if (string.IsNullOrEmpty(accessToken)) { bool ctrlCAsInput = false; if (Host.Name == "ConsoleHost") { ctrlCAsInput = Console.TreatControlCAsInput; Console.TreatControlCAsInput = true; } var connection = PnPConnectionHelper.InstantiateGraphDeviceLoginConnection(LaunchBrowser, Host, NoTelemetry, AzureEnvironment); if (Host.Name == "ConsoleHost") { Console.TreatControlCAsInput = ctrlCAsInput; } return(connection); } else { // TODO KZ: GetConnectionWithToken? return(PnPConnectionHelper.InstantiateGraphAccessTokenConnection(accessToken, NoTelemetry)); } }
/// <summary> /// Connect using provided credentials or the current credentials /// </summary> /// <returns>PnPConnection based on credentials authentication</returns> private PnPConnection ConnectCredentials(PSCredential 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); } } } return(PnPConnectionHelper.InstantiateSPOnlineConnection(new Uri(Url), credentials, TenantAdminUrl, NoTelemetry, AzureEnvironment)); }
/// <summary> /// Connect using the parameter set APPONLYCLIENTIDCLIENTSECRETURL /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectAppOnlyClientIdCClientSecretUrl() { return(PnPConnectionHelper.InstantiateSPOnlineConnection(new Uri(Url), AADDomain, ClientId, ClientSecret, TenantAdminUrl, false, AzureEnvironment)); }
private PnPConnection ConnectManagedIdentity() { WriteVerbose("Connecting to the Graph with the current Managed Identity"); return(PnPConnectionHelper.InstantiateManagedIdentityConnection(this, TenantAdminUrl)); }
/// <summary> /// Connect using the parameter set ACCESSTOKEN /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectAccessToken() { return(PnPConnectionHelper.InstantiateWithAccessToken(!string.IsNullOrEmpty(Url) ? new Uri(Url) : null, AccessToken, TenantAdminUrl)); }
/// <summary> /// Connect using the parameter set APPONLYAAD /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectAppOnlyWithCertificate() { if (ParameterSpecified(nameof(CertificatePath))) { if (!Path.IsPathRooted(CertificatePath)) { CertificatePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, CertificatePath); } if (!File.Exists(CertificatePath)) { throw new FileNotFoundException("Certificate not found"); } X509Certificate2 certificate = CertificateHelper.GetCertificateFromPath(CertificatePath, CertificatePassword); if (PnPConnection.CurrentConnection?.ClientId == ClientId && PnPConnection.CurrentConnection?.Tenant == Tenant && PnPConnection.CurrentConnection?.Certificate.Thumbprint == certificate.Thumbprint) { ReuseAuthenticationManager(); } return(PnPConnectionHelper.InstantiateConnectionWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate, true)); } else if (ParameterSpecified(nameof(CertificateBase64Encoded))) { var certificateBytes = Convert.FromBase64String(CertificateBase64Encoded); var certificate = new X509Certificate2(certificateBytes, CertificatePassword); if (PnPConnection.CurrentConnection?.ClientId == ClientId && PnPConnection.CurrentConnection?.Tenant == Tenant && PnPConnection.CurrentConnection?.Certificate.Thumbprint == certificate.Thumbprint) { ReuseAuthenticationManager(); } return(PnPConnectionHelper.InstantiateConnectionWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate)); } else if (ParameterSpecified(nameof(Thumbprint))) { X509Certificate2 certificate = CertificateHelper.GetCertificateFromStore(Thumbprint); if (certificate == null) { throw new PSArgumentException("Cannot find certificate with this thumbprint in the certificate store.", nameof(Thumbprint)); } // Ensure the private key of the certificate is available if (!certificate.HasPrivateKey) { throw new PSArgumentException("The certificate specified does not have a private key.", nameof(Thumbprint)); } if (PnPConnection.CurrentConnection?.ClientId == ClientId && PnPConnection.CurrentConnection?.Tenant == Tenant && PnPConnection.CurrentConnection?.Certificate.Thumbprint == certificate.Thumbprint) { ReuseAuthenticationManager(); } return(PnPConnectionHelper.InstantiateConnectionWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate)); } else { throw new ArgumentException("You must either provide CertificatePath, Certificate or CertificateBase64Encoded when connecting using an Azure Active Directory registered application"); } }
/// <summary> /// Sets up the connection using the information provided through the cmdlet arguments /// </summary> protected void Connect() { if (!string.IsNullOrEmpty(Url) && Url.EndsWith("/")) { Url = Url.Substring(0, Url.Length - 1); } PnPConnection connection = null; var latestVersion = PnPConnectionHelper.GetLatestVersion(); if (!string.IsNullOrEmpty(latestVersion)) { WriteUpdateMessage(latestVersion); } PSCredential credentials = null; if (Credentials != null) { credentials = Credentials.Credential; } WriteVerbose($"Using parameter set '{ParameterSetName}'"); // Connect using the used set parameters switch (ParameterSetName) { case ParameterSet_GRAPHWITHAAD: connection = ConnectGraphWithAad(); break; //case ParameterSet_SPOMANAGEMENT: // connection = ConnectSpoManagement(); // break; case ParameterSet_DEVICELOGIN: connection = ConnectDeviceLogin(); break; case ParameterSet_GRAPHDEVICELOGIN: connection = ConnectGraphDeviceLogin(null); break; case ParameterSet_NATIVEAAD: connection = ConnectNativeAAD(ClientId, RedirectUri); break; case ParameterSet_APPONLYAAD: connection = ConnectAppOnlyAad(); break; case ParameterSet_APPONLYAADPEM: connection = ConnectAppOnlyAadPem(); break; case ParameterSet_APPONLYAADThumb: connection = ConnectAppOnlyAadThumb(); break; case ParameterSet_APPONLYAADCER: connection = ConnectAppOnlyAadCer(); break; case ParameterSet_AADWITHSCOPE: connection = ConnectAadWithScope(credentials, AzureEnvironment); break; case ParameterSet_ACCESSTOKEN: connection = ConnectAccessToken(); break; case ParameterSet_TOKEN: connection = ConnectToken(); break; case ParameterSet_APPONLYCLIENTIDCLIENTSECRETURL: connection = ConnectAppOnlyClientIdCClientSecretUrl(); break; case ParameterSet_APPONLYCLIENTIDCLIENTSECRETAADDOMAIN: connection = ConnectAppOnlyClientIdCClientSecretAadDomain(); break; case ParameterSet_ADFSCERT: connection = ConnectAdfsCertificate(); break; case ParameterSet_ADFSCREDENTIALS: connection = ConnectAdfsCredentials(credentials); break; case ParameterSet_MAIN: connection = ConnectCredentials(credentials); break; } // Ensure a connection instance has been created by now if (connection == null) { // No connection instance was created throw new PSInvalidOperationException("Unable to connect using provided arguments"); } // Connection has been established WriteVerbose($"PnP PowerShell Cmdlets ({Assembly.GetExecutingAssembly().GetName().Version}): Connected to {Url}"); PnPConnection.CurrentConnection = connection; if (CreateDrive && PnPConnection.CurrentConnection.Context != null) { var provider = SessionState.Provider.GetAll().FirstOrDefault(p => p.Name.Equals(SPOProvider.PSProviderName, StringComparison.InvariantCultureIgnoreCase)); if (provider != null) { if (provider.Drives.Any(d => d.Name.Equals(DriveName, StringComparison.InvariantCultureIgnoreCase))) { SessionState.Drive.Remove(DriveName, true, "Global"); } var drive = new PSDriveInfo(DriveName, provider, string.Empty, Url, null); SessionState.Drive.New(drive, "Global"); } } if (PnPConnection.CurrentConnection.Url != null) { var hostUri = new Uri(PnPConnection.CurrentConnection.Url); Environment.SetEnvironmentVariable("PNPPSHOST", hostUri.Host); Environment.SetEnvironmentVariable("PNPPSSITE", hostUri.LocalPath); } else { Environment.SetEnvironmentVariable("PNPPSHOST", "GRAPH"); Environment.SetEnvironmentVariable("PNPPSSITE", "GRAPH"); } if (ReturnConnection) { WriteObject(connection); } }
/// <summary> /// Connect using the parameter set APPONLYAADThumb /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectAppOnlyAadThumb() { return(PnPConnectionHelper.InitiateAzureADAppOnlyConnection(new Uri(Url), ClientId, Tenant, Thumbprint, TenantAdminUrl, NoTelemetry, AzureEnvironment)); }