PnP PowerShell: Connect-PnPOnline using ClientID and ClientSecret

Requirement: Connect to SharePoint Online using PnP PowerShell Connect-PnPOnline with AppID and AppSecret.

How to Connect to SharePoint Online using PnP PowerShell AppID and AppSecret?

PnP PowerShell is a PowerShell module that provides a set of cmdlets for working with SharePoint and SharePoint Online. I have a PnP PowerShell script scheduled in the Windows Task scheduler that runs every 5 minutes. I need the script to connect to SharePoint Online unattended. Although I can store user names and passwords in the script, I would rather not do that as passwords are regularly changed as per the security policy.

The App method of authenticating allows us to run scripts without prompting credentials – username and password. Here are the steps to create a new app in SharePoint Online:

Step 1: Register a SharePoint Client ID

Register a new app in the app registry. Say you need to connect to the SharePoint Online site “https://tenant.sharepoint.com/sites/marketing”, Navigate to the URL: https://tenant.sharepoint.com/Sites/Marketing/_layouts/15/AppRegNew.aspx, and register a new app principal. Here is how to generate a client id and client secret in SharePoint Online:

  1. Click on the “Generate” button for both the “Client Id” and “Client Secret” fields. 
  2. Provide a name to the principal. I’ve entered “Task Scheduler Script”
  3. For domain and redirect URL, use “localhost” and “https://localhost” as the redirect URL.
  4. Copy the Client ID and Client Secret fields and click on the “Create” button to register the app principal. You should receive a confirmation message stating, “The app identifier has been successfully created.”
    connect-pnponline appid appsecret
You can register an App ID with never expiring app secret in Azure AD! Here is how: How to Register a Never Expiring App ID Secret with Azure AD?

Step 2: Assign Permission to the App Principal

Once the app principal is registered, the next step is to grant permission to the app principal on SharePoint Online. We can scope it to the tenant, site collection, or web levels. Let’s grant this app principal “Full Access” rights on the site collection.

  1. Navigate to https://tenant.sharepoint.com/sites/marketing/_layouts/15/appinv.aspx
  2. In the “App Id” field, enter the “Client Id” you copied in the previous step and click on the “Lookup” button. This loads “Title”, “App Domain” and “Redirect URL” values matching the entered App Id that we created and allows us to set the app’s permissions. In the “Permission Request XML:”, Enter the following and click on the “Create” button:
    • <AppPermissionRequests AllowAppOnlyPolicy=”true”><AppPermissionRequest Scope=”http://sharepoint/content/sitecollection” Right=”FullControl” /></AppPermissionRequests>
    • Similarly, to grant tenant-level permissions, use the following:
      <AppPermissionRequests AllowAppOnlyPolicy=”true”><AppPermissionRequest Scope=”http://sharepoint/content/tenant” Right=”FullControl” /> </AppPermissionRequests> How to Connect to SharePoint Online using Connect-PnPOnline AppID and AppSecret
  3. Click on the “Trust it” button to grant the app permission to access the SharePoint site collection with full access rights.
    Connect to SharePoint Online using PnP PowerShell AppID and AppSecret

Here I’ve configured “Full Control” in this site collection. You can also use: Read-Only, Write, Full Control on Lists, Webs, Site collections, or even tenant. Refer https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/add-in-permissions-in-sharepoint

Connect to SharePoint Online using Connect-PnPOnline ClientId and ClientSecret

Now, you can connect to SharePoint Online with AppId and AppSecret (technically from any application!)

#Site collection URL
$SiteURL = "https://crescent.sharepoint.com/sites/marketing/"

#Connect to SharePoint Online with ClientId and ClientSecret
Connect-PnPOnline -Url $SiteURL -ClientId "3c85uc19-f1b9-41ba-8c16-c3281x09b82" -ClientSecret "1KLekxb775bhs/C3*aqqWE6Gs13u4="

Get-PnPContext

In case you get the “Connect-PnPOnline : Token request failed.” error, check your AppId and AppSecret are correct. Or it may be expired, and by default, its expiration date is one year! You can register an AppID from the Azure AD management portal’s App registration section and set the duration to “Never Expire”. And then Grant access to that AppId from SharePoint.

If you get “Exception has been thrown by the target of an invocation,” that simply means your Client ID or Client secret is wrong or you have not been granted permissions.

Conclusion

In conclusion, connecting to a SharePoint site using a Client ID and Client Secret is a secure and efficient way to authenticate PowerShell scripts. By registering a client ID, creating a client secret, and granting permissions, you can use the Connect-PnPOnline cmdlet to connect to a SharePoint site and perform various operations using PnP PowerShell. It’s important to keep the client secret secure and make sure to test the connection before using it in the production environment.

If you’d like to connect to SharePoint Online using Azure Active Directory App ID and App Secret, Use: How to Connect to SharePoint Online using Azure AD App ID from PowerShell?

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

29 thoughts on “PnP PowerShell: Connect-PnPOnline using ClientID and ClientSecret

  • Unfortunately, the PNP.PowerShell Scripts no longer work, since they use ACS Tokens, which have been Deprecated by Microsoft.

    Therefore, you may want to utilize the Microsoft Graph REST API, per the instructions below.

    https://www.sharepointdiary.com/2023/04/how-to-connect-to-microsoft-graph-api-from-powershell.html

    To Test your REST Requests/Responses, Permissions and so forth, use the Microsoft Graph Explorer Utility.

    https://developer.microsoft.com/en-us/graph/graph-explorer

    Reply
  • getting error when trying to read subsite . even if scope has been given at site collection level. also unable to traverse through the document repository

    Reply
  • When do we need to use this solution and when do we need to use your other solution in your other blog?: https://www.sharepointdiary.com/2022/10/connect-to-sharepoint-online-using-azure-ad-app-id-from-powershell.html

    Reply
  • For those that are receiving the following “Unexpected Error” message looking up your Client ID and the “App Permission Request XML”, please use the following steps that worked for me:

    I had to replace all the exclamation points because in powershell when you use it as a cut and paste it comes in as rich text.
    So cut and past the XML into word pad, retype the ” so it looks normal, cut and paste it back into the XML box,and boom!

    Hope this helps!

    Reply
  • I get the error “Sorry, something went wrong
    An unexpected error has occurred.” in Step 2.2. whether I try Site or Tenant level permissions

    Reply
  • Hi Salaudeen Rajack,
    Thanks for sharing this ,it is helpful to every one.
    I have tried testing the above scenario in my Test tenant with SharePoint Admin user.
    I am able to register sharepoint app but i am unable to assign permission to app principal. it is returning error

    Sorry, something went wrong
    An unexpected error has occurred.
    TECHNICAL DETAILS

    Troubleshoot issues with Microsoft SharePoint Foundation.
    Correlation ID: 63ce9ca0-909d-3000-44a4-cf0a5b33fdaa

    Date and Time: 3/6/2023 10:19:17 PM

    I have tried working on different test tenants(No Azure Subscription) with Global admin, sharepoint admin . i am facing this error. i wanted to upload files in sharepoint using client id and client secret. i feel the above scenario you have mentioned is suitable but getting error while assigning permission .please guide through this. Thanks in Advance.

    Reply
  • Hi Salaudeen,

    Can we use the same steps for onedrive to get clientid and client secret. I believe it is used for sharepoint the above steps. May I know how do I use clientid and client secret using powershell script for onedrive accounts. I’am able to access the sharepoint sites but not the onedrive accounts. Please advice.

    Reply
  • Hi, would it work with sharepoint 2016 on premises?

    Reply
    • I received HTTP 400 when I tried against SP2016 on-premises:

      Connect-PnPOnline: The remote server returned an error: (400) Bad Request. – {“error”:”invalid_request”,”error_description”:”AADSTS90002: Tenant ‘3ace9085-3525-498c-a381-59bb1767e0c2’ not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.\r\nTrace ID: b83204b7-48c1-42e3-b3ea-e4c52c214300\r\nCorrelation ID: d58441dd-2824-4ac9-bc4a-aa3954113e00\r\nTimestamp: 2023-08-25 15:51:20Z”,”error_codes”:[90002],”timestamp”:”2023-08-25 15:51:20Z”,”trace_id”:”b83204b7-48c1-42e3-b3ea-e4c52c214300″,”correlation_id”:”d58441dd-2824-4ac9-bc4a-aa3954113e00″,”error_uri”:”https://accounts.accesscontrol.windows.net/error?code=90002″}

      Reply
  • For Scope, use “http://…” (as in image) instead of “https://…” (as in code snippet). Otherwise the app won’t have full control.

    Reply
  • I see the following error after following these steps:

    The remote server returned an error: (401) Unauthorized.

    Reply
    • Make sure DisableCustomAppAuthentication is set to False.

      Set-SPOTenant -DisableCustomAppAuthentication $false

      Reply
  • Hi.
    I am not able to get List Items if I use client ID and secret.

    Here is my Xml

    I am able to get all list names but as I soon as I try to get items of list, no result will be shown.

    Any Idea?

    Regards Umer

    Reply
  • Change it to ClientId and ClientSecret

    Reply
  • other than using app password, can you use app id or secret id using CSOM?

    Reply
  • Hi,

    When I try to connect I get following issue:

    Connect-PnPOnline : A parameter cannot be found that matches parameter name ‘AppId’.

    Reply
  • Thank you Salaudeen, very useful!

    Reply
  • How secure is this?

    Reply
  • I am getting Token Request failed issue.

    Reply
  • Hello after following above steps are you able to do Get-PnPList ?? I am still getting 401- Unauthorized.. Shouldn’t that is the whole purpose of doing above exercise.. can you pls. check at your end and confirm..

    ThankS!

    Reply
  • Hey,

    it was necessary for the second part to https://crescent-ADMIN.sharepoint.com/ in order to not have an access denied with SPO.

    Reply
    • Yes! If you are granting tenant level access, It should be the SharePoint Admin center URL you have to visit and create the App ID and grant permission!

      Reply
  • Is it safe to store the client ID and client secret in the file as plain text? Just curious.

    Reply
    • My question was poorly worded. What’s the next step to using the secret securely?

      Reply
    • Either using a credential manager (PNP has one I think, just unsure whether it can store app-regs). Then there is the possibility using environment Variables.

      Reply
  • as you have mentioned the Apps can be created using the azure portal. However, I am not able to authenticate using that app id and secret

    Reply
  • Very useful ! works perfectly, thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *