SharePoint Online: The remote server returned an error (401) Unauthorized” Error in PowerShell

Khushboo Kumari 112 Reputation points
2023-06-24T18:36:08.93+00:00

Hi, I want to store my output directly on SharePoint folder under document. For this I tried to access the SharePoint by using the Azure ad application keys. Client id, tenant id and secret key with API permission and want to create a folder but getting “The remote server returned an error (401) Unauthorized” Error in PowerShell. How can I resolve it. Please tell me as soon as possible.

Thanks!

Microsoft 365 and Office | SharePoint | Development
Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. RaytheonXie_MSFT 40,481 Reputation points Microsoft External Staff
    2023-06-26T07:58:52.0033333+00:00

    Hi @Khushboo Kumari,

    I will recommend you to upload certificate to Azure Key vault. You need to get certificate before connect to sharepoint online. Please check the following document
    https://learn.microsoft.com/en-us/azure/key-vault/certificates/quick-create-powershell

    Here is the sample PowerShell code to get certificate from Azure Key Vault and Connect to SharePoint with PnP

    # connect to your Azure subscription  
    Connect-AzAccount -Subscription "<subscription id>" -Tenant "<tenant id>"  
    Get-AzSubscription | fl  
    Get-AzContext  
      
    # Specify Key Vault Name and Certificate Name  
    $VaultName = "<azure key vault name>"  
    $certName = "certificate name as it stored in key vault"  
      
    # Get certificate stored in KeyVault (Yes, get it as SECRET)  
    $secret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $certName  
    $secretValueText = ($secret.SecretValue | ConvertFrom-SecureString -AsPlainText )  
      
    # connect to PnP  
    $tenant = "contoso.onmicrosoft.com" # or tenant Id  
    $siteUrl = "https://contoso.sharepoint.com"  
    $clientID = "<App (client) Id>" # Azure Registered App with the same certificate and API permissions configured  
    Connect-PnPOnline -Url $siteUrl -ClientId $clientID -Tenant $tenant -CertificateBase64Encoded $secretValueText
    
    
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Khushboo Kumari 112 Reputation points
    2023-06-28T05:57:08.44+00:00

    I am unable to generate or import the certificate in azure key Vault. Getting error. How can I resolve it?

    User's image


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.