PnPPowerShellを使用したSharePointOnlineでのアプリのみの認証

Azure AD Appのみの認証は、M365サービスへの認証と、データの読み取り、データのアップロード、自動化スクリプトを介したバックエンドジョブの実行などの操作に使用されています。Microsoftは、Azure ADに登録されているアプリケーションに証明書ベースの認証を使用して、M365または任意のクラウドサービスに対して認証することをお勧めします。CBAは、ユーザーのIDを検証するための非常に堅牢で安全なメカニズムです。 

この記事では、私が最近遭遇したユースケースについて説明したいと思います。以前は、SharePoint App Only認証を使用しています。これはACS(Azure Controlサービス)の概念であり、サイトコレクションの管理者はサイトコレクションに/_layouts/appregnew.aspxを追加することで、クライアントIDとクライアントシークレットを作成できます。アプリケーションで。ただし、このACSアプリのみのアクセストークン方式を使用する場合の問題はほとんどありません。

  • 認証は安全ではありません。MSFTは、AzureADアプリのみの認証に切り替えることをお勧めします。
  • アプリケーションが複数のサイトコレクションと通信するようにする場合は、複数のクライアントIDとシークレットを作成する必要があり、処理が面倒になります。

ACSトークンベースの認証の詳細については、参照セクションを参照してください。

幸いなことに、Azure ADアプリでは、SharePointのAPIアクセス許可に「Sites.Selected」という新しいアクセス許可が追加されました。これにより、AzureADアプリは単一のクライアントと証明書の詳細を使用して複数のサイトコレクションに対して認証できます。 

証明書を使用したこのAzureADアプリのみの認証に進む前に、Azure ADの証明書ベースの認証(別名CBA)とは何かを理解しようとします。AzureADには2種類のCBAがあります。 

  1. フェデレーションADFSを使用した証明書ベースの認証
  2. AzureAD証明書ベースの認証

フェデレーションADFSを使用した証明書ベースの認証

以前は、CBAを実装するために、ADFSサービスをユーザーとAzureADの間にデプロイする必要がありました。ADFSを使用するCBAは、X.509証明書を使用してAzureADに対して認証します。

  • ここで、ユーザーは自分の資格情報とデバイスにインストールされた証明書を使用してアプリケーションに署名します。
  • ADFSはユーザーの資格情報と証明書を検証し、成功するとアクセストークンをユーザーに渡してアプリケーションにアクセスします。

AzureAD証明書ベースの認証

Azure AD CBAである最新バージョンでは、ADFSの構成と展開は必要ありません。ユーザーはAzureADと直接対話し、アプリケーションに対して認証できます。

ADFSおよびAzureADCBAを使用したCBAの詳細については、参照セクションに記載されている記事を参照してください。

前提条件

  • PnP.Powershellバージョン1.10.0。このバージョンでは、CBAを使用した認証が更新されていることに注意してください。

  • PowerShellバージョン5.1以降
  • PowerShellコマンドの実行に使用されるアカウントには、「グローバル管理者」権限が必要です。

AzureADアプリを作成する

次に、APIアクセス許可「サイト」を使用してAzureADアプリを作成する手順を実行します。タイプ「アプリケーション」の「選択済み」。次に、このAzure ADアプリを使用して、複数のサイトコレクションに対して認証します。記事を正しく実行するには、最新のPnPPowershellバージョンがインストールされている必要があります。

ステップ1

管理者としてPowerShellISEまたはコマンドウィンドウを開きます。

ステップ2

以下のPSコマンドを実行してアプリケーションを登録します。以下のコマンドを実行しているアカウントに「グローバル管理者」権限があることを確認してください。アカウントでMFA(Multi-Factor Authentication Enabled)がある場合は、プロンプトに従います

Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive

SharePointOnlineサイトに接続するための証明書ベースの認証

SharePointOnlineサイトに接続するための証明書ベースの認証

ステップ3

認証が成功すると、必要なアーティファクトをチェックして同意フローを開始するために60秒待つことを示す以下のメッセージが表示されます。

SharePointOnlineサイトに接続するための証明書ベースの認証

ステップ4

アプリを登録してから、証明書と指紋を作成するために、もう一度認証するように求められます。プロンプトに従います

SharePointOnlineサイトに接続するための証明書ベースの認証

ステップ5

これで、以下のように認証が成功すると同意がポップアップ表示されます。アプリ名(この場合はSPSites Selected)と、承認およびキャンセルするオプションが表示されます。

SharePointOnlineサイトに接続するための証明書ベースの認証

[アプリ情報]をクリックして、アプリの詳細を確認することもできます。

ステップ6

[同意する]をクリックして同意することに同意すると、コマンド出力ウィンドウから次の情報が表示されます。

SharePointOnlineサイトに接続するための証明書ベースの認証

次の値があります、

  • Pfxファイル:証明書に関連付けられた公開鍵と秘密鍵の両方の情報が含まれています。これは組織外で共有しないでください。
  • Cerファイル:公開鍵とデバイス(この場合はサーバー)に関する情報が含まれています。これは通常、パートナーと交換されます。
  • 指紋:アプリケーションへの認証に使用される証明書に関連付けられた安全なキー。
  • Base64Encoded:これはASCII文字列形式の証明書情報です。

クライアントID、指紋、およびPfxファイルとCerファイルの場所のみをメモする必要があります。

上記の手順は、AzureADアプリケーションが「Sites.Selected」である必要なアクセス許可で作成されていることを確認します。これは、特定のサイトに対してのみ認証するようにAzureADアプリを構成できるようになったことを意味します。

AzureADアプリへのアクセスを許可する

ここで、Azure ADアプリへのアクセスを許可するには、次の一連のコマンドを実行します。

ステップ1

グローバル管理者の資格情報を持つPnPPowerShellモジュールを使用して、テナントのSharePoint管理者URLにログインします。

Connect-PnPOnline -Url "https://contoso-admin.sharepoint.com" -Interactive

SharePointOnlineサイトに接続するための証明書ベースの認証

ステップ2

認証時に、PnP管理シェルが実行できる権限に関する次の情報を取得します。

ここでは、組織に代わって同意するか、チェックを外したままにすることができます。[組織を代表して同意する]をオンにした場合、他のユーザーは同意を求められません。

ステップ3

次のコマンドを実行して、アプリに権限を付与します。アプリに付与できる権限は、「読み取り」または「書き込み」の2セットのみであることに注意してください。

Grant-PnPAzureADAppSitePermission -AppId 'YOUR APP ID HERE' -DisplayName 'APP DISPLAY NAME HERE' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write

SharePointOnlineサイトに接続するための証明書ベースの認証

検証

ステップ1

権限が付与されているサイトに接続して、アプリへのアクセスを検証します。問題なくコンテンツが表示されるはずです。この場合、以前の接続が存在する場合は、以前のPnP接続から切断します。

Disconnect-PnPOnline

ステップ2

以下のコマンドを入力して、他にPnP接続が存在しないことを確認します。

Get-PnPConnection

「現在の接続にはSharePointコンテキストがありません」というエラーが表示されるはずです。

SharePointOnlineサイトに接続するための証明書ベースの認証

ステップ3

次に、AzureADアプリのクレデンシャルを使用してSharePointサイトに接続します。

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo2" -ClientId "AZURE AD APP ID" -Thumbprint "CERT THUMP PRINT" -Tenant "YOUR TENANT DOMAIN"

アプリID(クライアントID)とフィンガープリントの値は、[AzureADアプリの作成]セクションの手順6で生成されることに注意してください。Azure ADポータルにログインし、[エンタープライズアプリケーション]でアプリを確認することで、AzureADから詳細を取得することもできます。

SharePointOnlineサイトに接続するための証明書ベースの認証

同様に、テナントドメインは、クイック起動から[Azure Active Directory]をクリックして、[プライマリドメイン]の値を探すことで取得できます。

SharePointOnlineサイトに接続するための証明書ベースの認証

ステップ4

次に、以下のコマンドを実行して、アプリが接続されているサイトを確認します。

Get-PnPSite

ステップ5

次に、以下のコマンドを実行して、このサイトコレクション内のすべてのリストのリストを取得します。

Get-PnPList

SharePointOnlineサイトに接続するための証明書ベースの認証

AzureADアプリがアクセスする必要のある他のサイトコレクションに対しても同じコマンドを実行できます。

ステップ6

アクセスが許可されていないサイトに接続して、アプリへのアクセスを検証します。403forbiddenエラーが表示されるはずです。

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "YOUR CLIENT ID" -Thumbprint "CERT THUMP PRINT" -Tenant "contosodev.onmicrosoft.com"

SharePointOnlineサイトに接続するための証明書ベースの認証

クライアントIDと証明書のサンププリントを使用してサイトに接続しているときにエラーがスローされないことに気付いたかもしれませんが、サイトの詳細またはリストのコンテンツを取得するときにエラーがスローされます。

完全なスクリプト

#Creating Azure AD App with Certificate Thumbprint.
Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive
#Connecting to SharePoint online Admin center using Global Admin Credentials
Connect-PnPOnline -Url "https://contosodev-admin.sharepoint.com" -Interactive
#Granting Access to Azure AD App for specific sites
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo2' -Permissions Write
#Disconnecting the previous connections
Disconnect-PnPOnline
#Validating the connection
Get-PnPConnection
#Connecting to SPO site using Azure AD App
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo1" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Gettting site details
Get-PnPSite
#Getting the list content
Get-PnPList
#Disconnecting from the Azure AD App connection
Disconnect-PnPOnline
#Connecting to SPO site using Azure Ad App with other site where access is not being granted.
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Get the site details
Get-PnPSite
#Get list content for site
Get-PnPList

結論

したがって、この記事では、

  • AzureAD証明書ベースの認証とは何ですか
  • さまざまな種類の認証
  • PnPモジュールを使用して、「Sites.Selected」APIアクセス許可を持つAzureADアプリを生成します。
  • Azure ADアプリへのアクセスを許可してから、アクセスを検証します。

参考文献

 このストーリーは、もともとhttps://www.c-sharpcorner.com/article/certificate-based-authentication-to-connect-to-sharepoint-online-sites/で公開されました。

#authentic #sharepoint #azure 

PnPPowerShellを使用したSharePointOnlineでのアプリのみの認証
Saul  Alaniz

Saul Alaniz

1655722800

Autenticación Solo De Aplicaciones En SharePoint online Mediante PnP

La autenticación solo de aplicaciones de Azure AD se usa para autenticarse en los servicios de M365 y realizar algunas operaciones, como leer los datos, cargar los datos o realizar algunos trabajos de back-end a través de scripts de automatización. Microsoft recomienda utilizar la autenticación basada en certificados para sus aplicaciones registradas en Azure AD para autenticarse en el M365 o en cualquier servicio en la nube. CBA es un mecanismo extremadamente robusto y seguro para validar la identidad del usuario. 

En este artículo, quiero hablar sobre el caso de uso que encontré recientemente. Anteriormente, estaba usando la autenticación de solo aplicación de SharePoint, que es el concepto de ACS (servicios de control de Azure), donde el administrador de la colección de sitios puede crear un ID de cliente y un secreto de cliente agregando /_layouts/appregnew.aspx en la colección de sitios y usando las credenciales del cliente. en aplicación. Sin embargo, hay algunos problemas al usar este método de token de acceso de solo aplicación de ACS.

  • La autenticación no es segura. MSFT recomienda cambiar a la autenticación de solo aplicación de Azure AD.
  • Si desea que su aplicación se comunique con múltiples colecciones de sitios, es necesario crear múltiples ID de cliente y secretos, lo que se vuelve engorroso de manejar.

Puede consultar más información sobre la autenticación basada en token de ACS en la sección de referencias.

La buena noticia es que en la aplicación Azure AD, los permisos de API para SharePoint vienen con nuevos permisos llamados "Sitios.Seleccionados", que permitirán que su aplicación Azure AD se autentique en varias colecciones de sitios utilizando un solo cliente y detalles del certificado. 

Antes de pasar a esta autenticación solo de aplicaciones de Azure AD mediante certificados, intentaremos comprender qué es la autenticación basada en certificados (también conocida como CBA) en Azure AD. Hay 2 tipos de CBA en Azure AD. 

  1. Autenticación basada en certificados con AD FS federado
  2. Autenticación basada en certificados de Azure AD

Autenticación basada en certificados con AD FS federado

Anteriormente, para implementar el CBA, los servicios de ADFS deben implementarse entre los usuarios y Azure AD. CBA con ADFS usa certificados X.509 para autenticarse en Azure AD.

  • Aquí el usuario inicia sesión en la aplicación con sus credenciales y también con el certificado instalado en sus dispositivos.
  • ADFS valida las credenciales y el certificado del usuario y, en caso de éxito, pasa tokens de acceso al usuario para acceder a las aplicaciones.

Autenticación basada en certificados de Azure AD

La última versión, que es Azure AD CBA, no necesita configuración ni implementación de AD FS. Los usuarios pueden interactuar directamente con Azure AD y autenticarse en las aplicaciones.

Para obtener más detalles sobre CBA con AD FS y Azure AD CBA, puede consultar los artículos mencionados en la sección de referencias.

requisitos previos

  • PnP.Powershell versión 1.10.0. Tenga en cuenta que la autenticación mediante CBA se actualiza en esta versión.

  • PowerShell versión 5.1 o posterior
  • La cuenta utilizada para ejecutar los comandos de PowerShell debe tener derechos de "Administrador global".

Crear una aplicación de Azure AD

Ahora seguiremos los pasos para crear la aplicación Azure AD, con permisos de API "Sitios. Seleccionado” de tipo “Aplicación”. Luego use esta aplicación de Azure AD para autenticarse en varias colecciones de sitios. Para poder seguir correctamente el artículo, es necesario tener instalada la última versión de PnP Powershell.

Paso 1

Abra PowerShell ISE o las ventanas de comandos como administrador.

Paso 2

Registre la aplicación ejecutando el siguiente comando PS. Asegúrese de que la cuenta que ejecuta los siguientes comandos tenga derechos de 'Administrador global'. Siga las indicaciones si la cuenta tiene MFA (autenticación multifactor habilitada)

Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 3

En una autenticación exitosa, recibirá el siguiente mensaje que dice que debe esperar 60 segundos para verificar los artefactos requeridos e iniciar el flujo de consentimiento.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 4

Se le pedirá que se autentique una vez más para registrar la aplicación y luego para crear un certificado y una huella digital. Siga las instrucciones de nuevo

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 5

Ahora tendrá una ventana emergente de consentimiento en una autenticación exitosa similar a la siguiente. Muestra el nombre de la aplicación (en este caso, SPSites seleccionado) y opciones para Aceptar y cancelar.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

También puede verificar los detalles de la aplicación haciendo clic en 'Información de la aplicación'.

Paso 6

Después de aceptar el consentimiento haciendo clic en 'Aceptar', debería ver la siguiente información en la ventana de salida del comando.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Tendrás los siguientes valores,

  • Archivo Pfx: incluye información de clave tanto pública como privada asociada al certificado. Esto no debe compartirse fuera de su organización.
  • Archivo cer: tiene clave pública y alguna información sobre el dispositivo (en este caso el servidor). Esto normalmente se intercambia con los socios.
  • Huella digital: una clave segura asociada con el certificado que se utiliza para autenticarse en la aplicación.
  • Base64Encoded: esta es la información del certificado en formato de cadena ASCII.

Debe anotar solo el ID del cliente, la huella digital y la ubicación de los archivos Pfx y Cer.

Los pasos anteriores confirman que la aplicación de Azure AD se crea con los permisos necesarios, que es "Sitios.Seleccionados". Esto significa que la aplicación de Azure AD ahora se puede configurar para autenticarse solo en sitios específicos.

Concesión de acceso a la aplicación Azure AD

Ahora, para otorgar acceso a la aplicación Azure AD, ejecute el siguiente conjunto de comandos.

Paso 1

Inicie sesión en la URL de administración de SharePoint para su arrendatario mediante el módulo PnP PowerShell con credenciales de administrador global.

Connect-PnPOnline -Url "https://contoso-admin.sharepoint.com" -Interactive

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 2

En la autenticación, obtendrá la siguiente información, sobre los permisos sobre lo que podría hacer el shell de administración de PnP.

Aquí puede dar su consentimiento en nombre de la organización o dejarlo sin marcar. Si marcó 'Consentimiento en nombre de su organización', no se solicitará el consentimiento de ningún otro usuario.

Paso 3

Otorgue el permiso a la aplicación ejecutando el siguiente comando. Tenga en cuenta que solo hay 2 conjuntos de permisos que puede otorgar a la aplicación, que es 'Lectura' o 'Escritura'.

Grant-PnPAzureADAppSitePermission -AppId 'YOUR APP ID HERE' -DisplayName 'APP DISPLAY NAME HERE' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Validación

Paso 1

Valide el acceso a la aplicación conectándose a sitios que tengan permisos. Debería ver el contenido sin ningún problema. En este caso, desconéctese de las conexiones PnP anteriores si existen conexiones anteriores.

Disconnect-PnPOnline

Paso 2

Valide que no exista otra conexión PnP escribiendo el siguiente comando.

Get-PnPConnection

Debería ver el error que dice "La conexión actual no tiene contexto de SharePoint".

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 3

Ahora conéctese al sitio de SharePoint usando las credenciales de la aplicación Azure AD.

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo2" -ClientId "AZURE AD APP ID" -Thumbprint "CERT THUMP PRINT" -Tenant "YOUR TENANT DOMAIN"

Tenga en cuenta que los valores de ID de aplicación (ID de cliente) y Huella digital se generan en el Paso 6 en la sección "Crear aplicación de Azure AD". También puede obtener los detalles de su Azure AD iniciando sesión en Azure AD Portal y revisando su aplicación en 'Aplicaciones empresariales'.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

De manera similar, el dominio del arrendatario se puede obtener haciendo clic en 'Azure Active Directory' desde el inicio rápido y buscando el valor 'Dominio principal'.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 4

Ahora verifique a qué sitio está conectada la aplicación ejecutando el siguiente comando.

Get-PnPSite

Paso 5

Ahora obtenga la lista de todas las listas en esta colección de sitios ejecutando el siguiente comando.

Get-PnPList

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Puede ejecutar los mismos comandos para cualquier otra colección de sitios a la que necesite acceder la aplicación Azure AD.

Paso 6

Valide el acceso a la aplicación conectándose a sitios a los que no se les otorga acceso. Debería ver el error 403 prohibido.

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "YOUR CLIENT ID" -Thumbprint "CERT THUMP PRINT" -Tenant "contosodev.onmicrosoft.com"

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Es posible que haya notado que no arroja ningún error al conectarse al sitio utilizando la ID del cliente y la impresión del certificado, sin embargo, arroja un error al obtener los detalles del sitio o el contenido de la lista.

Guión completo

#Creating Azure AD App with Certificate Thumbprint.
Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive
#Connecting to SharePoint online Admin center using Global Admin Credentials
Connect-PnPOnline -Url "https://contosodev-admin.sharepoint.com" -Interactive
#Granting Access to Azure AD App for specific sites
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo2' -Permissions Write
#Disconnecting the previous connections
Disconnect-PnPOnline
#Validating the connection
Get-PnPConnection
#Connecting to SPO site using Azure AD App
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo1" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Gettting site details
Get-PnPSite
#Getting the list content
Get-PnPList
#Disconnecting from the Azure AD App connection
Disconnect-PnPOnline
#Connecting to SPO site using Azure Ad App with other site where access is not being granted.
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Get the site details
Get-PnPSite
#Get list content for site
Get-PnPList

Conclusión

Por lo tanto, en este artículo, hemos aprendido sobre

  • ¿Qué es la autenticación basada en certificados de Azure AD y
  • los diferentes tipos de autenticación
  • utilizando el módulo PnP para generar la aplicación Azure AD con los permisos de API 'Sitios.Seleccionados'.
  • Otorgar acceso a la aplicación Azure AD y luego validar el acceso.

Referencias

 Esta historia se publicó originalmente en https://www.c-sharpcorner.com/article/certificate-based-authentication-to-connect-to-sharepoint-online-sites/

#authentic #sharepoint #azure 

Autenticación Solo De Aplicaciones En SharePoint online Mediante PnP
Oral  Brekke

Oral Brekke

1652759520

CSom-node: SharePoint Client Object Model (CSOM) API for Node.js

SharePoint Client Object Model (CSOM) API for Node.js

The library provides a SharePoint Client Object Model (CSOM) API for Node.js applications.

The current version supports SharePoint Online CSOM library (v 16) The remote authentication is performed via Claims-Based Authentication.

Installation

$ npm install csom-node

API

CSOM API - currently only Core object library for JavaScript is supported plus some additional packages listed below

AuthenticationContext - represents an object that provides credentials to access SharePoint Online resources.

The list of supported CSOM API packages

core

taxonomy

userprofile

policy

Usage

Authentication

Authenticate with user credentials

var csomapi = require('csom-node');

var settings = {
    url: "https://contoso.sharepoint.com/",
    username: "jdoe@contoso.onmicrosoft.com",
    password: "password"
};

csomapi.setLoaderOptions({url: settings.url});  //set CSOM library settings

var authCtx = new AuthenticationContext(settings.url);
authCtx.acquireTokenForUser(settings.username, settings.password, function (err, data) {
    
    var ctx = new SP.ClientContext("/");  //set root web
    authCtx.setAuthenticationCookie(ctx);  //authenticate
    
    //retrieve SP.Web client object
    var web = ctx.get_web();
    ctx.load(web);
    ctx.executeQueryAsync(function () {
        console.log(web.get_title());
    },
    function (sender, args) {
        console.log('An error occured: ' + args.get_message());
    });
      
});

Authenticate with app principal credentials (client id & client secret)

var csomapi = require("csom-node");
 
var settings = {
    url: "https://contoso.sharepoint.com/",
    clientId: "YOUR-GUID-GOES-HERE",
    clientSecret: "YOUR-CLIENT-SECRET-GOES-HERE"
};
 
csomapi.setLoaderOptions({url: settings.url});  //set CSOM library settings
 
var authCtx = new AuthenticationContext(settings.url);
authCtx.acquireTokenForApp(settings.clientId, settings.clientSecret, function (err, data) {
    
    var ctx = new SP.ClientContext("/");  //set root web
    authCtx.setAuthenticationCookie(ctx);  //authenticate
    
    //retrieve SP.Web client object
    var web = ctx.get_web();
    ctx.load(web);
    ctx.executeQueryAsync(function () {
        console.log(web.get_title());
    },
    function (sender, args) {
        console.log('An error occured: ' + args.get_message());
    });
      
});

Working with List Items

The following example demonstrates how to perform CRUD operations against list items:


var csomapi = require('csom-node');

var settings = {
    url: "https://contoso.sharepoint.com/",
    username: "jdoe@contoso.onmicrosoft.com",
    password: "password"
};

csomapi.setLoaderOptions({ url: settings.url, serverType: 'local', packages: [] });


var authCtx = new AuthenticationContext(settings.url);
authCtx.acquireTokenForUser(settings.username, settings.password, function(err, data) {

    var ctx = new SP.ClientContext("/");
    authCtx.setAuthenticationCookie(ctx); //authenticate

    var web = ctx.get_web();
    console.log("1. Read list items");
    readListItems(web, "Tasks", function(items) {
        items.get_data().forEach(function(item) {
            console.log(item.get_fieldValues().Title);
        });
        console.log('Tasks have been read successfully');
        console.log("2. Create list item");
        createListItem(web, "Tasks", function(item) {

            console.log(String.format('Task {0} has been created successfully', item.get_item('Title')));
            console.log("3. Update list item");
            updateListItem(item,function(item) {
                console.log(String.format('Task {0} has been updated successfully', item.get_item('Title')));
                console.log("4. Delete list item");
                deleteListItem(item,function() {
                    console.log('Task has been deleted successfully');
                },logError);

            },logError);
            
        }, logError);

    }, logError);

});


function logError(sender, args) {
    console.log('An error occured: ' + args.get_message());
}


function readListItems(web, listTitle, success, error) {
    var ctx = web.get_context();
    var list = web.get_lists().getByTitle(listTitle);
    var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
    ctx.load(items);
    ctx.executeQueryAsync(function() {
            success(items);
        },
        error);
}

function createListItem(web, listTitle,success,error) {
    var ctx = web.get_context();
    var list = web.get_lists().getByTitle(listTitle);
    var creationInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(creationInfo);
    listItem.set_item('Title', 'New Task');
    listItem.update();
    ctx.load(listItem);
    ctx.executeQueryAsync(function () {
            success(listItem);
        },
    error);
}


function updateListItem(listItem,success,error) {
    var ctx = listItem.get_context();
    listItem.set_item('Title', 'New Task (updated)');
    listItem.update();
    ctx.load(listItem);
    ctx.executeQueryAsync(function () {
        success(listItem);
    },
    error);
}

function deleteListItem(listItem, success, error) {
    var ctx = listItem.get_context();
    listItem.deleteObject();
    ctx.executeQueryAsync(function () {
        success();
    },
    error);
}

Visual Studio Code screenshot

alt tag

Author: VGrem
Source Code: https://github.com/vgrem/CSOMNode 
License: MIT license

#node #javascript #sharepoint 

CSom-node: SharePoint Client Object Model (CSOM) API for Node.js
Oral  Brekke

Oral Brekke

1652752140

SPSave Webpack Plugin

SPSave Webpack Plugin 

This is a webpack plugin that allows you upload generated assets to a SharePoint site. This uses the spsave plugin to authenticate and upload to SharePoint.

Installation

Important!

The latest version (2.x as of now) of the plugin supports webpack 4.x and doesn't have backward compatibility with webpack 3 or 2.

For webpack, earlier than 4.x version, explicitly use 1.x version:

$ npm install spsave-webpack-plugin@~1.0.8 --save-dev

For webpack 4.x and higher, use regular install:

$ npm install spsave-webpack-plugin --save-dev

Basic Usage

The plugin will upload all your webpack's assets to SharePoint using spsave. Just add the plugin to your webpack config as follows:

const path = require('path');

const SPSaveWebpackPlugin = require('spsave-webpack-plugin');
const root = path.join.bind(path, path.resolve(__dirname));

const webpackConfig = {
  entry: './index.js',
  output: {
    path: root('dist'),
    filename: 'bundle.js'
  },
  plugins: [new SPSaveWebpackPlugin({
            "coreOptions": {
                "checkin": true,
                "checkinType": 1,
                "siteUrl": "[your sharepoint site URL]"
            },
            "credentialOptions": {
                    /* See https://github.com/s-KaiNet/node-sp-auth#params for authentication options */
            },
            "fileOptions": {
                "folder": "Style Library/dist"
            }
        })]
};
module.exports = webpackConfig;

This will upload the dist/bundle.js to the specified folder: SharePoint library result

Configuration

Since the Webpack plugin is based on the spsave node module, all configuration options are virtually identical. The only difference is the fact that you do not need to specify fileOptions other that the destination folder since the uploaded files will be the ones emitted by the Webpack build. NOTE: This plugin is not intended to be used when in a hot-reloading Webpack setup.

Version History

Version 2.0

  • Webpack 4.0 support (not compatible with older Webpack versions anymore)
  • Support for HTML Webpack Plugin
  • Fixed issue with wrong folder structure on SharePoint (flat folder structure instead of intended folder structure)

Maintainers: Yohan Belval @yohanb and Sergei Sergeev @s-KaiNet

Author: Yohanb
Source Code: https://github.com/yohanb/spsave-webpack-plugin 
License: MIT license

#node #webpack #sharepoint 

SPSave Webpack Plugin
Oral  Brekke

Oral Brekke

1652744460

SPsave: Save Files in SharePoint using Node.js Easily

spsave

Nodejs module for saving files in SharePoint:

  • SharePoint 2013, 2016
  • SharePoint Online

spsave depends heavily on another module sp-request and use it to send REST queries to SharePoint. sp-request, in turns, depends on the module responsible for SharePoint authentiation from node js - node-sp-auth.
CHANGELOG


How to use:

Install:

npm install spsave --save-dev

Usage:

var spsave = require("spsave").spsave;

spsave(coreOptions, creds, fileOptions)
.then(successHandler)
.catch(errorHandler);

Using with gulp

You have following options:

Use official gulp plugin for spsave - gulp-spsave

Use spsave inside gulp tasks or in watchers like this:

var spsave = require("spsave").spsave;
 
 gulp.task('spsave', function(cb) {
     
   spsave(coreOptions, creds, fileOptions)
   .then(function(){
       cb();
   }).catch(cb);
   
 );

Use both approaches. First one is handy if you are processing files in a stream, for example you need minimize, concatenate and then upload. The second can be used if you want just upload files and that's it.

Using with SharePoint hosted apps (uploading to app web)

Please refer to this page (at the bottom)

options:

Starting from spsave 3.x all options divided by logical categories (in order):

  • core options
  • credentials
  • file(s) options

Core options:

  • siteUrl - required, string url of the site
  • checkin - optional, boolean to allow the files to be checked in/published
  • checkinType - optional number, used when checkin options is true
    • 0 - minor
    • 1 - major
    • 2 - overwrite
    • 3 - nocheckin - special case if you don't want your file to be checked-in on every file upload. In that case you file will remain checked-in after upload and you should either manually upload it, or run spsave again with other checkinType
  • checkinMessage - optional string, you can provide your own checkin message, otherwise default will be used
  • notification - optional boolean, when true, spsave will notify about successful upload using node-notifier module
  • filesMetaData - optional, array of IFileMetaData:
    • fileName - required, string file name
    • metadata - metadata object

Credentials:

spsave 3.x implicitly depends on another module used for SharePoint authentication from node js - node-sp-auth. For spsave credentials param you need to pass exactly the same object, as for node-sp-auth credentialsOptions object. That also means that spsave supports all authentication options supported by node-sp-auth. On Recipes page you can find a bit more samples.
You can also pass a null as credentials, in that case spsave will ask you for credentials and will store your credentials in a user folder in an encrypted manner (everything is handled by node-sp-auth actually).

File(s) options:

File options used to tell spsave how to find\load the file to be uploaded to SharePoint. When one is used, others are ignored. There are three file options supported: file content, glob and vinyl file.

File content options:

  • folder - required string, site-relative url to folder, which will be used to save your file. For example for library http://sp2013/sites/dev/SiteAssets folder will be equal to SiteAssets, SiteAssets/subfolder for sub folder. If the folder doesn't exist, spsave will create that folder and all sub folders if required (full hierarchy)
  • fileName - required, string file name
  • fileContent - required, string or buffer file content (binary files supported, you can do something like this: fileContent: fs.readFileSync('app/img/logo.png'))

Glob options (you can provide a mask to read all or certain files from the file system):

  • glob - required, string or string array, i.e. 'build/css/style.css' or ['build/css/*.*']. Pattern is similar to node-glob module.
  • base - optional string, if you want to preserve folders structure inside SharePoint folder, you can provide a base for you files. For example when using glob ['build/css/*.*'] and base: 'build', all css files will be loaded under [SharePoint folder]/css
  • folder - optional string, site-relative url to folder, which will be used to save your file. The same as for file content options. If the folder is null or empty, spsave will try to resolve folder using base option provided

Vinyl options. If you are familiar with vinyl and vinyl-fs you can provide vinyl file directly:

  • file - required, vinyl File object
  • folder - optional string, site-relative url to folder, which will be used to save your file. The same as for file content options. If the folder is null or empty, spsave will try to resolve the folder using base of vinyl file

Don't be scared and confused with a lot of options and take a look at the Recipes page. You can find all possible scenarios with spsave, input params and expected output.

successHandler

Handler gets called upon successful file upload.

errorHandler

Handler gets executed in case of exception inside spsave. Accepts error object as first argument for callback.

Samples

Use Recipes page to see all different options available with spsave.

Basic usage:

var coreOptions = {
    siteUrl: '[sp url]',
    notification: true,
    checkin: true,
    checkinType: 1
};
var creds = {
    username: '[username]',
    password: '[password]',
    domain: '[domain (on premise)]'
};

var fileOptions = {
    folder: 'SiteAssets',
    fileName: 'file.txt',
    fileContent: 'hello world'
};
spsave(coreOptions, creds, fileOptions)
.then(function(){
    console.log('saved');
})
.catch(function(err){
    console.log(err);
});

Development:

I recommend using VS Code for development. Repository already contains some settings for VS Code editor. Before creating Pull Request you need to create an appropriate issue and reference it from PR.

  1. git clone https://github.com/s-KaiNet/spsave.git
  2. cd spsave
  3. git checkout -b myfeature dev
  4. npm run build - restores dependencies and runs typescript compilation
  5. gulp live-dev - setup watchers and automatically runs typescript compilation, tslint and tests when you save files

Tests:

  1. npm test. As a result /reports folder will be created with test results in junit format and code coverage. Additionally test reports will be available in a console window.

Integration testing:

  1. Rename file /test/integration/config.sample.ts to config.ts.
  2. Update information in config.ts with appropriate values (urls, credentials, environment).
  3. Run gulp test-int.

Need help on SharePoint with Node.JS? Join our gitter chat and ask question! Gitter chat

Author: s-KaiNet
Source Code: https://github.com/s-KaiNet/spsave 
License: MIT license

#node #sharepoint #javascript #typescript 

SPsave: Save Files in SharePoint using Node.js Easily
Oral  Brekke

Oral Brekke

1652737020

SPpurge: Delete Files From SharePoint Document Libraries using Node.js

SPPurge - simple client to delete files from SharePoint document libraries   

Node.js module for file deletion from SharePoint document libraries.

Supported SharePoint versions

  • SharePoint Online
  • SharePoint On-Prem (2019, 2016, 2013)

How to use

Install

npm install sppurge --save-dev

Usage

const sppurge = require('sppurge').default;

const context = {/*...*/};
const options = {/*...*/};

sppurge(context, options)
  .then(successHandler)
  .catch(errorHandler);

Arguments

Context

  • siteUrl - SharePoint site (SPWeb) url [string, required]
  • creds
    • username - user name for SP authentication [string, optional in case of some auth methods]
    • password - password [string, optional in case of some auth methods]

Additional authentication options:

Since SP client (sp-request), which is used in sppurge, had received additional SharePoint authentication methods, they are also supported in sppurge.

For more information please check node-sp-auth credential options and wiki pages.

Options

  • folder - relative folder in SharePoint to concat with filePath [string, optional, default: `` (empty string)]
  • filePath - relative file path, with extention [string, required in general, optional if localFilePath and localBasePath are both provided]
  • localFilePath - local full path to file [string, optional]
  • localBasePath - relative folder base path within project directory [string, optional]

The result file path is formed based on the following rule:

  • siteUrl + folder + filePath
  • If filePath is empty, then:
    • filePath = path.resolve(localFilePath).replace(path.resolve(localBasePath), '')

successHandler

The callback gets called upon successful file deletion.

errorHandler

The callback gets executed in case of an exception inside sppurge. Accepts error object as first argument for callback.

Basic usage example (delete a single file)

const sppurge = require('sppurge').default;

const context = { /* auth context */ };

const options = {
  folder: '/_catalogs/masterpage/spf/module_name',
  filePath: '/scripts/dummy-file.js'
};

sppurge(context, options)
  .then(deletionResults => {
    console.log('A file has been deleted');
  })
  .catch(err => {
    console.log('Core error has happened', err);
  });

Basic usage example (delete a folder)

const { Delete } = require('sppurge');

const context = { /* auth context */ };
const sppurge = new Delete();

sppurge.deleteFolder(context, '/sites/site/folder/repative/path')
  .then(deletionResults => {
    console.log('A folder has been deleted');
  })
  .catch(err => {
    console.log('Core error has happened', err);
  });

Within Gulp task

const gulp = require('gulp');
const watch = require('gulp-watch');      // Allows more than gulp.watch, is recommended
const spsave = require('gulp-spsave');    // Optional SPSave, but what is the reason to use SPPurge without SPSave?
const sppurge = require('sppurge').default;
const path = require('path');

const config = require('./gulp.config'); // Getting settings for SPPurge and SPSave

gulp.task('watch-assets', () => {
  return watch(config.watch.assets, function (event) {
    // Base local folder path, e.g. 'src' from which
    // project's files are mapped to SharePoint folder
    const watchBase = config.watch.base;

    // When file is deleted event value is "unlink"
    if (event.event === 'unlink') {
      const sppurgeOptions = {
        folder: config.sppurge.options.spRootFolder,
        filePath: path.resolve(event.path).replace(path.resolve(watchBase), '')
      };
      // OR:
      // const sppurgeOptions = {
      //   folder: config.sppurge.options.spRootFolder,
      //   localFilePath: event.path,
      //   localBasePath: watchBase
      // };
      sppurge(config.sppurge.context, sppurgeOptions)
        .then((res) => console.log(`File has been deleted: ${res}`))
        .catch((err) => console.log('Error', err));
    } else {
      // Saving files to SharePoint
      gulp.src(event.path, {
        base: watchBase
      }).pipe(
        spsave(
          // SPSave's core options, see more in spsave documentation
          config.spsave.coreOptions,
          // node-sp-auth / spsave credential object
          config.spsave.creds
        )
      );
    }
  });
});

Create React App usage scenario

Delete JS's build folder then upload all files from/build folder

One of the architectural decisions in CRA is using hashes as a part of assets filenames. This allows avoiding issues related to browser cache. However, it can be challenging in terms of deployment to SharePoint assets folders, as all filenames are different on each build. The further sample shows a simple use case approach of deleting files based on folder and name pattern.

const { AuthConfig } = require('node-sp-auth-config');
const sppurge = require('sppurge').default;
const spsave = require('spsave').spsave;

// client-side project's assets destination folder
const targetFolder = '_catalogs/masterpage/assets/cra-project';

const authConfig = new AuthConfig({
  configPath: './config/private.json',
  encryptPassword: true,
  saveConfigOnDisk: true
});

authConfig.getContext().then(({ siteUrl, authOptions: creds }) => {

  const deleteOptions = {
    folder: `${targetFolder}/static/js`,
    fileRegExp: new RegExp('(.*)/(.*)\.(js|map)', 'i'), // include .js, .map to delete
    // filePath: 'SiteAssets/trash.txt' // for single file deletion
  };

  const spsaveCoreOptions = {
    siteUrl,
    notification: true,
    checkin: true,
    checkinType: 2 // 0=minor, 1=major, 2=overwrite
  };

  const spsaveFileOptions = {
    glob: [ 'build/**/*.*' ],
    base: 'build',
    folder: targetFolder
  };

  return sppurge({ siteUrl, creds }, deleteOptions)
    .then(_ => console.log('=== Files Deleted ==='));
    .then(_ => spsave(spsaveCoreOptions, creds, spsaveFileOptions))
    .then(_ => console.log('=== Files Uploaded ==='));

}).catch(console.warn);

Passwords storage

To eliminate any local password storing if preferable to use any two-way hashing technique, like cpass.

Author: Koltyakov
Source Code: https://github.com/koltyakov/sppurge 
License: MIT license

#node #javascript #tasks #sharepoint 

SPpurge: Delete Files From SharePoint Document Libraries using Node.js
Oral  Brekke

Oral Brekke

1652722260

SPDeployment: A Command Line tool To Deploy All Kind Of Files

SPDeployment

SPDeployment is a command line tool to deploy all kind of files to SharePoint / Office 365.

With the help of a SPDeployment.json file in your project you can configure which files in which folders should be deployed to which targets.

A new feature is to watch for file changes and deploy only changed files.

Installation

You can install the SPDeployment tool with npm.

npm install spdeployment -g

Usage

Create a SPDeployment.json file

You can use the file in the sample folder to get started.

It has the following elements:

{
  "DefaultEnvironment": "Test",
  "Sites": [
    {
      "FastMode": false,
      "Environment": "Test",
      "Name": "AppForTest",
      "Url": "https://your-tenant.sharepoint.com/sites/test",
      "Username": "",
      "Password": "",
      "Files": [
        {
          "Source": "dist\\Style Library",
          "Destination": "/Style Library",
          "Exclude": ".*.bundle,.*.map",
          "Include": "",
          "Clean": true
        }
      ]
    }
  ]
}

With DefaultEnvironment you can specify which environment should be deployed when you run spd without any parameters. Then you can specify multiple sites which must have the following parameters:

  • FastMode: Make deployment faster, if destination folder structure already exists and your destination libraries does not require checkin/checkout/publishing
  • Environment : Any string to define an environment
  • Name : Any string to define a name for this site. Must be unique.
  • Url : The target site url
  • (optional) Username : The username or an empty string. If it is empty, spd will look for spdeployment.credentials.json, then in the environment variable spdeployment:username (Process->User->Machine) or finally prompt for it .
  • (optional) Password : The password or an empty string. If it is empty, spd will look for spdeployment.credentials.json, then in the environment variable spdeployment:password (Process->User->Machine) or finally prompt for it .
  • Files : An array containing
    • the local source folder (with escaped \)
    • the remote destination folder (in url format with /)
    • (optional) Regex to exclude files/folders
    • (optional) Regex to include files/folders
    • (optional) Deletes all files from the folder before deployment

Now add this file to your project root.

Optional: spdeployment.credentials.json file

To not have the credentials for deployments within the spdeployment.json file you can optionally create a spdeployment.credentials.json which you can then exclude from source control. The file has only the following two attributes:

{
  "Username": "",
  "Password": ""
}

Or if you have to deal with ADFS and/or multi-factor authentication you can set SPDeployment to use the cookie store of your Chrome Browser:

{
  "FromChromeCookies": "True"
}

Usage: Login in Chrome with ADFS and/or multi-factor authentication and leave Chrome open. Now SPDeployment will use the cookies from the session for authentication.

If spd detects this file, it ignores the Username/Password attributes from SPDeployment.json. If you would like to not save credentials on disk, you can add two environment variables (lookup order: Process->User->Machine):

  • spdeployment:username
  • spdeployment:password

I want to set properties after uploading files (e.g. for .webpart files)

Just add a [YOUR_FILE_WITH_EXTENSION].spdproperties file with the following format:

{
  "FieldName1": "NewValue",
  "FieldName2": "NewValue"
}

spd will automatically set the properties after uploading the file.

Run it

To run it, open a command line within your project root folder and run:

spd without any parameters to deploy all sites for the default environment

spd env:yourenvname to deploy all sites with the yourenvname environment

spd name:somename to deploy the site with the somename name

spd watch to deploy all sites for the default environment and watch for changes

spd env:yourenvname watch to deploy all sites with the yourenvname environment and watch for changes

spd name:somename watch to deploy the site with the somename name and watch for changes

Author: mwiedemeyer
Source Code: https://github.com/mwiedemeyer/SPDeployment 
License: MIT license

#node #command #sharepoint 

SPDeployment: A Command Line tool To Deploy All Kind Of Files
Oral  Brekke

Oral Brekke

1652714700

Sharepoint-file: Sharepoint File Operations

sharepoint-file

A command-line utility for Sharepoint file operations

ℹ️ Currently supports only download of individual files from an online Sharepoint site / file storage.

Installation or update

$ npm install -g sharepoint-file

Usage

$ spfile task args

Available tasks: (use --help for more info)

fetch [options] <FILEURL> [filepath] ... Fetches a file and shows its content or saves it
                                         <FILEURL>  The full Sharepoint URL to the file
                                         [filepath] File name or file path to save to
      [-u] ............................. User credentials as emailaddress:password

                                         Example: spfile fetch https://your.sharepoint.com/path/foo.json
                                         Example: spfile fetch https://your.sharepoint.com/path/bar.pdf bar.pdf

login [options] <HOSTURL> .............. Authenticates with Sharepoint explicitly
                                         <HOSTURL> The Sharepoint host URL
      [-u] ............................. User credentials as emailaddress:password

                                         Example: spfile login https://your.sharepoint.com

logout ................................. Invalidates your Sharepoint session explicitly

Options:

--silent ............................... Suppresses most console output

Author: Timegrip
Source Code: https://github.com/timegrip/sharepoint-file 
License: MIT license

#node #sharepoint #file 

Sharepoint-file: Sharepoint File Operations
Oral  Brekke

Oral Brekke

1652707320

Gulp-spsync-creds: Gulp Plugin for Synchronizing Local Files

gulp-spsync-creds

Gulp plugin for synchronizing local files with a SharePoint library

This Gulp plugin is based on gulp-spsync which has been created by Wictor Wilen. The difference with gulp-spsync is that this plugin makes use for client credentials (username and password) in order to upload and/or download files. This makes the plugin usable for both SharePoint Online and on-premises environments.

Installation

Run the following command to install the gulp-spsync-creds plugin:

$ npm install gulp-spsync-creds

Usage

Uploading files

For uploading files, you can add the following code to your gulpfile.js:

var gulp = require('gulp');
var spsync = require('gulp-spsync-creds').sync;

gulp.src('./src/**/*')
.pipe(spsync({
    "username": "<username>",
    "password": "<password>",
    "site": "<site-url>",
}));

Downloading files

For downloading files, you can add the following code to your gulpfile.js:

var gulp = require('gulp');
var spdwn = require('gulp-spsync-creds').download;

spdwn({
    "site": "<site-url>",
    "username": "<username>",
    "password": "<password>",
    "startFolder": "<relative-folder-location>"
}).pipe(gulp.dest("src"));

Information: it currently retrieves all files of the given path and the ones of three folders deep.

Options

The plugin has the following options that can be configured:

username

Type: String Default: null

Sets the username to be used for the sync action.

password

Type: String Default: null

Sets the password to be used for the sync action.

site

Type: String Default: ""

Sets the site URL to where the files should be uploaded.

startFolder

Type: String Default: ""

Choose the name of the folder location it has to starts from. This is useful when you have a nested folder structure. Example: if your folder structure is like this src/template1/_sp/_catalogs, and you set the startFolder option to _sp, it will strip out all the folder names before including _sp. You end up with _catalogs.

Important: this property can also be used to specify the location from where you want to download files.

libraryPath New property - v2.3.0

Type: string Default: ""

The libraryPath property can be used if you want to define a default library path to where you want to upload your files.

By default the plugin uploads the files based on their file location (under your source folder).

src
|_ _catalogs
   |_ masterpage
      |_ your-folder
         |_ file1.html

So in the above case, file1.html will be uploaded to the master page gallery (_catalogs/masterpage) in a your-folder folder.

When you define the libaryPath to for example: documents. The plugin will upload the files to that specific document library with the folder structure. So in this case it will be documents/_catalogs/masterpage/your-folder/file1.html.

update_metadata

Type: Boolean Default: false

Specify if you want to update the metadata of files you are uploading. If this is set to true, you will have to pass the file metadata via the files_metadata option.

files_metadata

Type: Object Default: []

With the files_metadata option you can specify the metadata of all the files you wish to upload. Example:

"fileMetadata": [
    {
        "name": "Item_Minimal.js",
        "metadata": {
            "__metadata": {
                "type": "SP.Data.OData__x005f_catalogs_x002f_masterpageItem"
            },
            "Title": "Item Minimal Template (via GULP)",
            "MasterPageDescription": "This is a display template added via gulp.",
            "ManagedPropertyMapping": "'Path','Title':'Title'",
            "ContentTypeId": "0x0101002039C03B61C64EC4A04F5361F38510660500A0383064C59087438E649B7323C95AF6",
            "DisplayTemplateLevel": "Item",
            "TemplateHidden": false,
            "TargetControlType": {
                "__metadata": {
                "type": "Collection(Edm.String)"
                },
                "results": [
                "SearchResults",
                "Content Web Parts"
                ]
            }
        }
    },
    {
        "name": "Control_Minimal.js",
            "metadata": {
            "__metadata": {
                "type": "SP.Data.OData__x005f_catalogs_x002f_masterpageItem"
            },
            "Title": "Control Minimal Template (via GULP)",
            "MasterPageDescription": "This is a display template added via gulp.",
            "ContentTypeId": "0x0101002039C03B61C64EC4A04F5361F38510660500A0383064C59087438E649B7323C95AF6",
            "DisplayTemplateLevel": "Control",
            "TemplateHidden": false,
            "TargetControlType": {
                "__metadata": {
                "type": "Collection(Edm.String)"
                },
                "results": [
                "SearchResults",
                "Content Web Parts"
                ]
            }
        }
    }
]

publish

Type: Boolean Default: false

With this option you can specify if you want to publish files after they are uploaded.

cache

Type: Boolean Default: false

If set to true the plugin caches library locations that already have been processed. Makes the watch tasks quicker.

associatedHtml (only for download actions)

Type: Boolean Default: true

With this property you can specify if you want to download all files (by default set to true) from a folder. This will also download the files that are associated to an HTML template like a page layout, master page and display template. If you set this property to false, the plugin only downloads the HTML files and leaves the ".aspx", ".master" and ".js" files in the folder.

verbose

Type: Boolean Default: false

If you wish to see all the plugin logging you can set this to true.

Author: Estruyf
Source Code: https://github.com/estruyf/gulp-spsync-creds 
License: MIT license

#node #gulp #sharepoint 

Gulp-spsync-creds: Gulp Plugin for Synchronizing Local Files
Sheldon  Grant

Sheldon Grant

1652700615

SP-screwdriver: Adds Missing & Abstracts SharePoint APIs

Screwdriver for SharePoint

Adds missing and abstracts SharePoint APIs for transparent usage in Node.js applications

SharePoint REST API is cool, but there are cases, then it's limited or even absent (e.g. MMD is not reachable trough REST API).

This library implements (or at least tries) some vital capabilities by wrapping legacy but still working SOAP services and by hacking HTTP requests mimicing JSOM/CSOM.

New in version 1.0.0

  • Code base is completely migrated to TypeScript.
  • node-sp-auth-config is integrated to the library.
  • Integration tests are added.

Supported SharePoint versions

  • SharePoint Online
  • SharePoint 2013
  • SharePoint 2016

Usage

Install

npm install sp-screwdriver --save

or

yarn add sp-screwdriver

Minimal setup

import { Screwdriver, IScrewdriverSettings } from 'sp-screwdriver';

const settings: IScrewdriverSettings = {
  // ...
};

const screw = new Screwdriver(settings);

// Wizard mode asks for credentials
screw.wizard().then(() => {

  screw.ups.getPropertiesFor({
    accountName: 'i:0#.f|membership|username'
  }).then(result => {
    // ...
  }).catch(console.log);

  screw.mmd.getAllTerms({
    serviceName: 'Taxonomy_5KSgChEZ9j15+7UVInQNRQ==',
    termSetId: '8ed8c9ea-7052-4c1d-a4d7-b9c10bffea6f'
  }).then(result => {
    // ...
  }).catch(console.log);

});

alternative:

import { Screwdriver } from 'sp-screwdriver';

const screw = new Screwdriver(); // Default settings
screw.init(); // private.json already should be on the disk
              // or raw auth parameters should be provided

screw.ups.getUserPropertyByAccountName({
  accountName: 'i:0#.f|membership|username',
  propertyName: 'SPS-Birthday'
}).then(result => {
  done();
}).catch(done);

APIs

User Profiles Service

  • getUserProfileByName (SOAP, /_vti_bin/UserProfileService.asmx)
  • modifyUserPropertyByAccountName (SOAP, /_vti_bin/UserProfileService.asmx)
  • getUserPropertyByAccountName (SOAP, /_vti_bin/UserProfileService.asmx)
  • getUserProfilePropertyFor (REST, /_api/sp.userprofiles.peoplemanager/getpropertiesfor)
  • getPropertiesFor (REST, /_api/sp.userprofiles.peoplemanager/getuserprofilepropertyfor)
  • setSingleValueProfileProperty (HTTP, /_vti_bin/client.svc/ProcessQuery)
  • setMultiValuedProfileProperty (HTTP, /_vti_bin/client.svc/ProcessQuery)

Manage Metadata Service (Taxonomy)

  • getTermSets (SOAP, /_vti_bin/TaxonomyClientService.asmx)
  • getChildTermsInTermSet (SOAP, /_vti_bin/TaxonomyClientService.asmx)
  • getChildTermsInTerm (SOAP, /_vti_bin/TaxonomyClientService.asmx)
  • getTermsByLabel (SOAP, /_vti_bin/TaxonomyClientService.asmx)
  • getKeywordTermsByGuids (SOAP, /_vti_bin/TaxonomyClientService.asmx)
  • addTerms (SOAP, /_vti_bin/TaxonomyClientService.asmx)
  • getAllTerms (HTTP, /_vti_bin/client.svc/ProcessQuery)
  • setTermName (HTTP, /_vti_bin/client.svc/ProcessQuery)
  • deprecateTerm (HTTP, /_vti_bin/client.svc/ProcessQuery)

Versions

Document versions

  • getVersions (SOAP, /_vti_bin/versions.asmx)
  • restoreVersion (SOAP, /_vti_bin/versions.asmx)
  • deleteVersion (SOAP, /_vti_bin/versions.asmx)
  • deleteAllVersions (SOAP, /_vti_bin/versions.asmx)

Item versions

  • getVersionCollection (SOAP, /_vti_bin/lists.asmx)

Item property bags

  • setItemProperties (HTTP, /_vti_bin/client.svc/ProcessQuery)

Possible SOAP services to implement

  • Alerts (/_vti_bin/alerts.asmx)
  • Authentication Web service (/_vti_bin/Authentication.asmx)
  • BDC Web Service (/_vti_bin/businessdatacatalog.asmx)
  • CMS Content Area Toolbox Info Web service (/_vti_bin/contentAreaToolboxService.asmx)
  • Copy Web service (/_vti_bin/Copy.asmx)
  • Document Workspace Web service (/_vti_bin/DWS.asmx)
  • Excel Services Web service (/_vti_bin/ExcelService.asmx)
  • Meetings Web service (/_vti_bin/Meetings.asmx)
  • People Web service (/_vti_bin/People.asmx)
  • Permissions Web service (/_vti_bin/Permissions.asmx)
  • Published Links Web service (/_vti_bin/publishedlinksservice.asmx)
  • Publishing Service Web service (/_vti_bin/PublishingService.asmx)
  • Search Web service (/_vti_bin/search.asmx)
  • SharePoint Directory Management Web service (/_vti_bin/sharepointemailws.asmx)
  • Sites Web service (/_vti_bin/sites.asmx)
  • Search Crawl Web service (/_vti_bin/spscrawl.asmx)
  • Users and Groups Web service (/_vti_bin/UserGroup.asmx)
  • User Profile Change Web service (/_vti_bin/userprofilechangeservice.asmx)
  • User Profile Web service (/_vti_bin/userprofileservice.asmx)
  • Views Web service (/_vti_bin/Views.asmx)
  • Web Part Pages Web service (/_vti_bin/webpartpages.asmx)
  • Webs Web service (/_vti_bin/Webs.asmx)
  • Workflow Web service (/_vti_bin/workflow.asmx)

...

Author: Koltyakov
Source Code: https://github.com/koltyakov/sp-screwdriver 
License: MIT license

#node #api #javascript #sharepoint 

SP-screwdriver: Adds Missing & Abstracts SharePoint APIs
Oral  Brekke

Oral Brekke

1652699880

Gulp Plugin for Synchronizing Local Files with A SharePoint Library

gulp-spsync

Gulp plugin for synchronizing local files with a SharePoint library

Features

  • Gulp plugin
  • Copies local files to a SharePoint Document libraries and galleries

How to use

  1. Prepare SharePoint by registering a SharePoint app using appregnew.aspx. Eg go to https://contoso.sharepoint.com/sites/site/_layouts/15/appregnew.aspx
  2. Click on Generate for both Client Id and Client Secret. For Title, App Domain and Redirect URI, write something you don't care about. Then click on Create
  3. Note down the Client Id and Client Secret, you will need it later
  4. Navigate to appinv.aspx, https://contoso.sharepoint.com/sites/site/_layouts/15/appinv.aspx, enter the client ID in the App Id box and press Lookup
  5. In the Permission Request XML text box enter the following XML and click Create (Note: FullControl is required to update assets in the Master Page gallery)
<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest
        Scope="http://sharepoint/content/sitecollection/web"
        Right="FullControl"/>
</AppPermissionRequests>
  1. In the following consent screen choose to trust the App by clicking on Trust It!
  2. Open a folder using Visual studio code
  3. Run npm install gulp to install the Gulp task runner
  4. Run npm install gulp-spsync to install to install the gulp-spsync
  5. Press Ctrl-Shift-P, type Task and choose to Configure Task Runner
  6. In the tasks.json file that is being created replace the contents with the following:
{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "tasks": [
        {
            "taskName": "default",
            "isBuildCommand": true,
            "showOutput": "silent"
        }
    ]
}	
  1. Create a new file in the root of your folder called gulpfile.js, and modify it as follows. This task will monitor all files in the Src folder
var gulp = require('gulp')
var sp = require('gulp-spsync')
gulp.task('default', function() {
return gulp.src('src/**/*.*').
    pipe(sp({
        "client_id":"3d271647-2e12-4ae5-9271-04b3aa67dcd3",
        "client_secret":"Zk9ORywN0gaGljrtlxfp+s5vh7ZyWV4dRpOXCLjtl8U=",
        "realm" : "",
        "site" : "https://contoso.sharepoint.com/sites/site",
        "verbose": "true"
    })).		
    pipe(gulp.dest('build'))
})
  1. Replace the client_id and client_secret parameters with the value for the App you just created
  2. Replace the site URL with your site URL
  3. Create a folder called Src (you can call it whatever you want, but the tasks above/below uses Src)
  4. Create sub folders to the Src folder where each Subfolder represents a Library in a site. You can alos create a subfolder called _catalogs and add a subfolder to that one called masterpage if you want to sync files to the Master Page Gallery.
  5. Add files as you want to these folders
  6. Press Ctrl-Shift-B to Build and let Gulp and gulp-spsync upload the files to SharePoint

Using Gulp watchers

You can use Gulp watchers (gulp-watch) to upload files as they are changed. The following gulpfile.js shows how to upload all files on build and then upload files incrementally when changed and saved.

You need to run npm install gulp-watch to install the Gulp watcher

var gulp = require('gulp')
var sp = require('gulp-spsync')
var watch = require('gulp-watch')

var settings = {
			"client_id":"...",
			"client_secret":"...",
			"realm" : "",
			"site" : "https://contoso.sharepoint.com/sites/site",
			"verbose": "true",
			"watch": true
		};
gulp.task('default', function() {
	return gulp.src('src/**/*.*')
		.pipe(watch('src/**/*.*'))
		.pipe(sp(settings))		
		.pipe(gulp.dest('build'))
})

Setting metadata for files

If you're files require metadata to be set when they are uploaded, you can pass in a metadata options (update_metadata, files_metadata).

Example:

var fileMetadata = [
    {
        name: 'Item_Minimal.js',
        metadata: {
            "__metadata": { type: "SP.Data.OData__x005f_catalogs_x002f_masterpageItem" },
            Title: 'Item Minimal Template (via GULP)',
            MasterPageDescription: 'This is a display template added via gulp.',
            ManagedPropertyMapping: "'Path','Title':'Title'",
            ContentTypeId: '0x0101002039C03B61C64EC4A04F5361F38510660500A0383064C59087438E649B7323C95AF6',
            DisplayTemplateLevel: 'Item',
            TargetControlType: {
                "__metadata": {
                    "type": "Collection(Edm.String)"
                },
                "results": [
                    "SearchResults",
                    "Content Web Parts"
                ]
            }
        }
    },
    {
        name: 'Control_Minimal.js',
        metadata: {
            "__metadata": { type: "SP.Data.OData__x005f_catalogs_x002f_masterpageItem" },
            Title: 'Control Minimal Template (via GULP)',
            MasterPageDescription: 'This is a display template added via gulp.',
            ContentTypeId: '0x0101002039C03B61C64EC4A04F5361F38510660500A0383064C59087438E649B7323C95AF6',
            DisplayTemplateLevel: 'Control',
            TargetControlType: {
                "__metadata": {
                    "type": "Collection(Edm.String)"
                },
                "results": [
                    "SearchResults",
                    "Content Web Parts"
                ]
            }
        }
    }
];

var settings = {
    "client_id":"...",
    "client_secret":"...",
    "realm" : "",
    "site" : "https://contoso.sharepoint.com/sites/site",
    "verbose": true,
    "update_metadata": true,
    "files_metadata": fileMetadata
};

Publishing files

By setting the publish setting, you can specify to publish your files when they are uploaded to the site.

var settings = {
    "client_id":"...",
    "client_secret":"...",
    "realm" : "",
    "site" : "https://contoso.sharepoint.com/sites/site",
    "verbose": true,
    "publish": true
};

Using nested folders (new in 1.4.0)

If you're using nested folders or deep structures, you can choose the name of the "start folder", using the startFolder option. Assume you have your SharePoint files under src/template1/_sp/_catalogs and src/template2/_sp/_catalogs/ then you can use "startFolder"="_sp" to make sure that the first folder names are stripped.

var gulp = require('gulp')
var sp = require('gulp-spsync')

var settings = {
			"client_id":"...",
			"client_secret":"...",
			"realm" : "",
			"site" : "https://contoso.sharepoint.com/sites/site",
			"verbose": "true",
            "startFolder":"_sp"
		};
gulp.task('default', function() {
	return gulp.src('src/**/_sp/**/*.*')
		.pipe(sp(settings))		
})

Author: Wictorwilen
Source Code: https://github.com/wictorwilen/gulp-spsync 
License: MIT license

#node #gulp #sharepoint #javascript 

Gulp Plugin for Synchronizing Local Files with A SharePoint Library
Oral  Brekke

Oral Brekke

1652684880

Passport.js Authentication Middleware for SharePoint Add-in

Passport.js authentication middleware for SharePoint add-in

Passport.js authentication strategy for SharePoint Online and SharePoint on-premise performing authentication via ACS.

This module allows you to perform SharePoint add-in authentication for your Node.js Express web application. Can be also integrated into other connect-based frameworks.

Install

npm install passport-sharepoint-addin

Usage

For detailed in-depth tutorial and configuration workflow please visit sample here - Express SharePoint add-in sample.

Basic setup

passport.use(new SharePointAddinStrategy({clientId: '', clientSecret: ''}, 'https://site.com/auth/sharepoint/callback', (profile: ISharePointProfile) => {
        return User.findOne({ 'sharepoint.loginName': profile.loginName })
            .then(user => {
                if (user) {
                    return user;
                }

                const newUser = new User();
                newUser.sharepoint.email = profile.email;
                newUser.sharepoint.loginName = profile.loginName;
                newUser.sharepoint.displayName = profile.displayName;
                return newUser.save();
            });
    }));

Need help on SharePoint with Node.JS? Join our gitter chat and ask question! 

Author: s-KaiNet
Source Code: https://github.com/s-KaiNet/passport-sharepoint-addin 
License: 

#node #expressjs #sharepoint #passport 

Passport.js Authentication Middleware for SharePoint Add-in
Oral  Brekke

Oral Brekke

1652670120

Expressjs-sp-addin: SharePoint Add-in with Express.js and PnP-JS-Core

SharePoint add-in with Express.js and PnP-JS-Core

This repository contains sample SharePoint add-in built with Node.js. Technologies used:

How to run

  1. On your SharePoint site open App registration page at https://company.sharepoint.com/sites/your_site/_layouts/15/appregnew.aspx and register a new app. Generate ClientId and ClientSecret, use ane Title, for App Domain put localhost:44355, for Redirect URI put https://localhost:44355/
  2. Take a note on generated credentials.
  3. Open SharePoint project from sharepoint-addin folder.
  4. Open AppManifest.xml and change ClientId attribute of RemoteWebApplication to your generated ClientId
  5. Deploy the app using Visual Studio (right click on a project -> Deploy)
  6. Wait for project to be deployed. Click on "Trust it" in a browser after deployment.
  7. Open command prompt at web-app folder.
  8. Run npm install
  9. Run npm run start. Wait for a while and you will see the server is started and message Listening on port 44355.
  10. Open your SharePoint site and click on the app. You will be redirected to the app home page.

How does it work

When you click on the app in SharePoint, you get redirected to auth/sharepoint/appredirect. The app extracts host url, creates a hash and stores it in Mongo. The the user is get authenticated. Authentication related data is stored inside session, the user information like login name and email are stored inside Mongo.

Need help on SharePoint with Node.JS? Join our gitter chat and ask question! 

Author: s-KaiNet
Source Code: https://github.com/s-KaiNet/expressjs-sp-addin 
License: 

#node #expressjs #sharepoint 

Expressjs-sp-addin: SharePoint Add-in with Express.js and PnP-JS-Core
Oral  Brekke

Oral Brekke

1652643960

A Powerful Command-line tool for Configuring SharePoint Site Columns

Engineer

Engineer is a powerful command-line tool to help track and consolidate SharePoint configuration changes in any number of environments. It's like version control for site columns, content types, lists, views, and more.

Getting Started

npm i -g sp-engineer

Once installed, you can type engineer into any console prompt to run Engineer commands. Use engineer -h to see a list of commands.

Start a New Project

engineer init

The init command creates env.js in the current working directory. This file contains important configuration information such as the SharePoint site URL and authentication settings. Any authentication configuration supported by node-sp-auth can be used as the auth settings in your env.js file.

Install Engineer Lists

Once your env.js file is set up, you're ready to install Engineer lists to your target SharePoint environment.

engineer install

Migrations

Engineer uses migrations to track configuration changes made to SharePoint. You can use migrations to create a queue of tasks that are executed in order on any number of target environments. Think of migrations like source control for your configuration operations.

New Migration

engineer make my-first-migration

The make command creates a file called migrations/YYYYMMDDHHMMSS-my-first-migration.js (YYYYMMDDHHMMSS is replaced by the current UTC timestamp). Feel free to open this file to see what's inside. By default, new migrations are configured to create a new list called My List when migrated.

Migrate

engineer migrate

The migrate command activates pending migrations. A new list called My List will be created on the target SharePoint site when this migration is activated.

Roll Back

engineer rollback

The rollback command retracts active migrations. Once rolled back, My List is deleted from the target SharePoint site.

Multiple Environments

You can create copies of env.js, allowing you to store authentication and configuration for multiple SharePoint environments. Use Engineer's --config option to switch environments when running any command.

engineer -c env/dev.js migrate
engineer -c env/prod.js migrate

Documentation

Find details on every Engineer command and migration API method in the official documentation, available at http://sp-engineer.org.

Explore Engineer Documentation

Engineer is inspired by Laravel migrations, and is made possible by PnP-JS-Core, node-pnp-js, and CSOMNode.

Author: Kyleschaeffer
Source Code: https://github.com/kyleschaeffer/engineer 
License: MIT license

#node #javascript #sharepoint 

A Powerful Command-line tool for Configuring SharePoint Site Columns
Excel  Tutorial

Excel Tutorial

1647056599

How to Add & Update Excel Data to SharePoint List using Power Automate

This video is a step-by-step tutorial on how to add and update your SharePoint list items from Excel Table data using Power Automate flows. 
We will create a template Excel file, where data to be imported to SharePoint will be loaded. The Template file will be made available for download from SharePoint Library (or OneDrive). Excel files with data rows will be uploaded to a SharePoint drop off library where Power Automate flow will be listening to start adding or updating the data from the Excel file (Table with rows) to SharePoint List.
Flow will track the status of the Excel file, Log updates & perform error handling, add & update SharePoint list data for most column types - Text, Date, Date & Time, Choice, Lookup, Person, Multi select choice, multi select person columns & more.
We will also look at getting lookup column ID from secondary SharePoint List.

Flow will check if row in Excel has an existing item in SharePoint. If yes, then flow will update SharePoint item from Excel row data else flow will create a New Item in SharePoint List.

This Power Apps Video covers the following:
✅ SharePoint List
✅ Excel Template from SharePoint List
✅ Add Excel data to SharePoint List using Power Automate
✅ Update Excel data to SharePoint List using Power Automate
✅ Add data validation & null checks in Excel & flow
✅ Date and time conversions
✅ Excel file import status logging & more.
✅ Performance & Limitations for large excel files with large number of rows, 256 row limits, pagination, 6 minutes delay for locked file status & more.

Table of Contents:
0:00 - Introduction to Add & Update Excel Table data to SharePoint using flow
0:47 - SharePoint List Scenario
2:08 - Import Excel data to SharePoint
2:41 - Create the Excel template file to Import to SharePoint
7:19 - Excel Data Validations
8:35 - Create Power Automate flow to add Excel Table rows to SharePoint List
24:33 - Add Null Checks in Flow
26:41 - SharePoint Date & Time Columns - Time Zone Conversions
29:25- Limitations & Performance for large data in Excel
32:27 - Update Excel File Status (file locked scenario when List Rows present in a Table action is called in flow)
35:51 - Add logic in flow to update SharePoint List data from excel file.
40:04 - Log results of Excel file import to SharePoint using Power Automate
41:42 - Subscribe to Reza Dorrani channel

🔗 Download ⬇️ Sample flows
https://github.com/rdorrani/Microsoft-Flow/tree/master/ExcelDataToSharePoint 

🔗 List rows present in a table (Excel Connector)
https://docs.microsoft.com/en-us/connectors/excelonlinebusiness/#known-issues-and-limitations-with-actions 

🔗 SharePoint connector
https://docs.microsoft.com/en-us/connectors/sharepointonline 

Subscribe: https://www.youtube.com/c/RezaDorrani/featured 

#powerautomate  #excel  #sharepoint  

How to Add & Update Excel Data to SharePoint List using Power Automate