PnP-PowerShell icon indicating copy to clipboard operation
PnP-PowerShell copied to clipboard

Connect-PnPOnline with certificates does not work

Open devmanlab opened this issue 7 years ago • 16 comments

###Notice: many issues / bugs reported are actually related to the PnP Core Library which is used behind the scenes. Consider carefully where to report an issue:###

Reporting an Issue or Missing Feature

I am getting exceptions that provide a little useful information when connecting using certificates and appId . At the same I can connect using simple administrator user credentials.

Expected behavior

I expect to see no errors and some initial information should be provided if authentication is successful

Actual behavior

PS C:\> Connect-PnPOnline -Tenant <tenant>.onmicrosoft.com -ClientId <AppIdGUID> -Thumbprint <THUMBFROMAZURE> -url https://<tenant>.sharepoint.com
Connect-PnPOnline : Exception has been thrown by the target of an invocation.
At line:1 char:1
+ Connect-PnPOnline -Tenant <tenant>.onmicrosoft.com -ClientId ffeef18d-5 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-PnPOnline], TargetInvocationException
    + FullyQualifiedErrorId : System.Reflection.TargetInvocationException,SharePointPnP.PowerShell.Commands.Base.ConnectOnline

PS C:\> Connect-PnPOnline -CertificatePath C:\pnp.pfx  -Tenant <tenant>.onmicrosoft.com -ClientId <AppIdGUID> -url https://<tenant>.sharepoint.com -Verbose
Connect-PnPOnline : Access denied.
At line:1 char:1
+ Connect-PnPOnline -CertificatePath C:\pnp.p ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-PnPOnline], CryptographicException
    + FullyQualifiedErrorId : System.Security.Cryptography.CryptographicException,SharePointPnP.PowerShell.Commands.Base.ConnectOnline

Steps to reproduce behavior

See samples above followed instruction

Which version of the PnP-PowerShell Cmdlets are you using?

  • [ ] PnP PowerShell for SharePoint 2013
  • [ ] PnP PowerShell for SharePoint 2016
  • [x] PnP PowerShell for SharePoint Online

What is the version of the Cmdlet module you are running?

PS C:\Users....\Documents\pfx> Get-Module SharePointPnPPowerShellOnline | Format-List

Name : SharePointPnPPowerShellOnline Path : C:\Users....\Documents\WindowsPowerShell\Modules\SharePointPnPPowerShellOnline\3.11.1907.0\SharePointPnP.PowerShell.Online.Commands.dll Description : SharePoint Patterns and Practices PowerShell Cmdlets for SharePoint Online ModuleType : Binary Version : 3.11.1907.0 NestedModules : {} ExportedFunctions : ExportedCmdlets : {Add-PnPAlert, Add-PnPApp, Add-PnPClientSidePage, Add-PnPClientSidePageSection...} ExportedVariables : ExportedAliases : {Add-PnPPnPProvisioningSubSite, Add-PnPProvisioningSequence, Add-PnPProvisioningSite, Apply-PnPProvisioningHierarchy...}

How did you install the PnP-PowerShell Cmdlets?

  • [ ] MSI Installed downloaded from GitHub
  • [x] Installed through the PowerShell Gallery with Install-Module
  • [ ] Other means

devmanlab avatar Jul 22 '19 21:07 devmanlab

Thank you for reporting this issue. We will be triaging your incoming issue as soon as possible.

ghost avatar Jul 22 '19 21:07 ghost

Hello I added a reference to a issue that was open about this, any news about this one @VesaJuvonen thank you!

get-itips avatar Aug 22 '19 18:08 get-itips

Hi @Damag3d, I tried both using thumbprint and pfx file directly following the sample, and both worked.

Can you verify that the AAD application is created with the correct permissions and that you have clicked the grant permission button before connection (and give it a minute before testing).

image

wobba avatar Aug 23 '19 07:08 wobba

I have the same issue.

SharePointPnPPowerShellOnline 3.13.1909.0

$certificatePassword = 'm0O3x;?hjtf#'
$secureCertificatePass = ConvertTo-SecureString -String $certificatePassword -AsPlainText -Force

Connect-PnPOnline `
    -CertificatePath "C:\....\DeploymentApp.pfx" `
    -Tenant <TENANT>.onmicrosoft.com `
    -ClientId fff6667e-1141-4bb5-ba3e-eaaf653975c6 `
    -Url https://<TENANT>.sharepoint.com `
    -CertificatePassword $secureCertificatePass `
    -IgnoreSslErrors `
    -Verbose

Result:

Connect-PnPOnline : Exception has been thrown by the target of an invocation. At line:6 char:1

  • Connect-PnPOnline `
  •   + CategoryInfo          : NotSpecified: (:) [Connect-PnPOnline], TargetInvocationException
      + FullyQualifiedErrorId : System.Reflection.TargetInvocationException,SharePointPnP.PowerShell.Commands.Base.ConnectOnline
    

More info

  • Generated a self-signed certificate. Recorded the password
  • Registered an Azure App. Uploaded a certificate to the app
  • Granted App permissions to the app
  • Granted admin consent

image

Zerg00s avatar Sep 12 '19 02:09 Zerg00s

@Zerg00s Can you run get-pnpexception after the error and see if there's a longer stack trace to help. Also, how did you create the certifcate?

@Damag3d did you resolve your issue?

wobba avatar Sep 12 '19 07:09 wobba

Thank you very much for helping, @wobba! Really appreciate your time.

This is the result of running Get-PnPException right after Connect-PnPOnline:

get-pnpexception

Message : Exception has been thrown by the target of an invocation. Stacktrace : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.SharePoint.Client.ClientContextExtensions.<>c__DisplayClass10_0.b__4(Object sender, WebRequestEventArgs webRequestEventArgs) at System.EventHandler`1.Invoke(Object sender, TEventArgs e) at Microsoft.SharePoint.Client.ClientRuntimeContext.OnExecutingWebRequest(WebRequestEventArgs args) at Microsoft.SharePoint.Client.ClientContext.GetWebRequestExecutor() at Microsoft.SharePoint.Client.ClientContext.d__b.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.SharePoint.Client.ClientContext.d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.SharePoint.Client.ClientContext.d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.SharePoint.Client.ClientContextExtensions.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.SharePoint.Client.ClientContextExtensions.ExecuteQueryRetry(ClientRuntimeContext clientContext, Int32 retryCount, Int32 delay, String userAgent) at SharePointPnP.PowerShell.Commands.Base.SPOnlineConnectionHelper.IsTenantAdminSite(ClientRuntimeContext clientContext) at SharePointPnP.PowerShell.Commands.Base.SPOnlineConnectionHelper.InitiateAzureAdAppOnlyConnectionWithCert(Uri url, String clientId, String tenant, Int32 minimalHealthScore, Int32 retryCount, Int32 retryWait, Int32 requestTimeout, String tenantAdminUrl, PSHost host, Boolean disableTelemetry, Boolean skipAdminCheck, AzureEnvironment azureEnvironment, X509Certificate2 certificate, Boolean certificateFromFile) at SharePointPnP.PowerShell.Commands.Base.ConnectOnline.ProcessRecord() at System.Management.Automation.CommandProcessor.ProcessRecord() ScriptLineNumber : 6

Replication steps

For the replication steps, I've uploaded the scripts here.

Zerg00s avatar Sep 12 '19 14:09 Zerg00s

Tested now. Created a new cert with New-PnPAzureCertificate -OutPfx foo.pfx -OutCert foo.cer -CertificatePassword $pw. Uploaded the .cer file and connected just fine with the .pfx file. So not sure what's failing. And I have the exact same permissions in the app as you have. I uploaded the .cer file from the Azure admin UI.

image

image

How did you create the certificate?

wobba avatar Sep 12 '19 15:09 wobba

@wobba I have installed the generated certificate to the store and then used Thumbprint instead of CertificatePath and CertificatePassword. This seems to work:

Connect-PnPOnline `
    -Thumbprint '637C2635E1E4478FB48A643B6EEB7F7C8920B7E4' `
    -Tenant <Tenant>.onmicrosoft.com `
    -ClientId fff6667e-1141-4bb5-ba3e-eaaf653975c6 `
    -Url https://<Tenant>.sharepoint.com

Get-PnPSite
# Returns results!

It means that something is wrong with CertificatePath approach. It does not seem to work.

Zerg00s avatar Sep 12 '19 15:09 Zerg00s

@wobba

This is the script for generating the certificates I was using: Create-SelfSignedCertificate.ps1

And this is how this script was run:

   # -------------------------------------------------------------------------------
    # Generate strong passwords for the certificate
    # -------------------------------------------------------------------------------
    Add-Type -AssemblyName System.Web 
    # "&" is converted to "\u0026" when using ConvertTo-Json, so we strip this off.
    $certificatePassword = [System.Web.Security.Membership]::GeneratePassword(12, 3) -replace "&","!"
    $encryptedCertPassword = ConvertTo-SecureString -String $certificatePassword -AsPlainText -Force

    # -------------------------------------------------------------------------------
    # Generate self-signed .cer and .pfx files
    # -------------------------------------------------------------------------------
    .\Create-SelfSignedCertificate.ps1 `
        -CommonName $certificateName `
        -StartDate (Get-Date).AddDays(-1) `
        -EndDate "2299-01-01" `
        -Password $encryptedCertPassword

I will try New-PnPAzureCertificate -OutPfx foo.pfx -OutCert foo.cer -CertificatePassword $pw approach and post the results in 1 hour or so.

Zerg00s avatar Sep 12 '19 15:09 Zerg00s

@wobba, thank you for your help. I have tried your approach with New-PnPAzureCertificate, but alas, I'm getting the same error.

This is how I generated the certificate:

$certificatePassword = '<Secret Pass>'
$secureCertificatePass = ConvertTo-SecureString -String $certificatePassword -AsPlainText -Force
New-PnPAzureCertificate -OutPfx foo.pfx -OutCert foo.cer -CertificatePassword $secureCertificatePass

image

Screenshot image

It works with a thumbprint though. Which is good news. But now I am super-curious why CertificatePath works for you and doesn't work in my case.

Zerg00s avatar Sep 12 '19 17:09 Zerg00s

Weird indeed and not sure why this is. Maybe you need to pull down the source code and debug 😉 Can you run fiddler and see if you spot a difference in the connect call with pfx and thumb print?

wobba avatar Sep 12 '19 17:09 wobba

@wobba

I've tried the same steps from a different PC and everything seems to be working perfectly. Very weird.

To troubleshoot what's not working - I tried hooking up fiddler and there is no traffic coming from Connect-PnPOnline -CertificatePath ... when an error occurs. So the commandlet fails during or right before connection is attempted. When everything is working using thumbnail - I see the traffic.

I will try to debug this locally in Visual studio when I have time.

Zerg00s avatar Sep 18 '19 15:09 Zerg00s

@Zerg00s Appreciate this. If you can nail down the exact scenario and repro that would indeed help.

wobba avatar Sep 19 '19 10:09 wobba

I'm encountering the same problem.

  • The -Certificatepath option throws Exception has been thrown by the target of an invocation.
  • The -Thumbprint option throws Connect-PnPOnline : Value cannot be null. Parameter name: certificate

ghost avatar Oct 24 '19 13:10 ghost

@wnzn any way you can debug this via the code? If I cannot repro, it's hard to figure out.

wobba avatar Oct 24 '19 14:10 wobba

@wobba Thanks for reaching out. I was looking into this when I noticed I had overlooked the following: New-PnPAzureCertificate -OutPfx foo.pfx -**OutCert** foo.cer -CertificatePassword $pw

I was creating certs using the -Out parameter. I can now connect without error. Sorry for this, I spent too long looking at it...

ghost avatar Oct 24 '19 14:10 ghost