次の方法で共有


Entra ID アプリケーションのアクセス許可を使用したアクセス許可の付与

SharePoint Online を使用する場合は、Entra ID でアプリケーションを定義できます。これらのアプリケーションには、SharePoint に対するアクセス許可だけでなく、Microsoft 365 の他のすべてのサービスに対するアクセス許可も付与できます。 このモデルは、SharePoint Online を使用している場合に推奨されるモデルです。オンプレミスで SharePoint を使用している場合は、こちらの説明に従って ACS に基づいて SharePoint Only モデルAzure使用する必要があります。

アプリ専用アクセス用の Entra ID アプリの設定

アプリのみの実行時に Entra ID では、証明書を使用して SharePoint CSOM/REST API へのアクセスを要求する必要があります。証明書とその秘密キーを持っているすべてのユーザーは、アプリとアプリに付与されたアクセス許可を使用できます。 以下の手順は、このモデルの設定についての説明です。

Entra ポータルを使用した Entra アプリケーションの作成

Entra アプリケーションを手動で作成する場合は、次の手順に従って Entra アプリケーションを作成して構成します。

  1. Entra Portal に移動し、[アプリケーション] をクリックし、左側ナビゲーションからアプリの登録をクリックします
  2. [ 新しい登録 ] ページをクリックします
  3. Entra アプリケーションの 名前 を指定します (例: Microsoft365AssessmentToolForWorkflow)
  4. [ パブリック クライアント/ネイティブ (モバイル & デスクトップ)] を選択し、リダイレクト URI として「 http://localhost 」と入力します
  5. [ 登録 ] をクリックすると、Entra アプリケーションが作成されて開きます
  6. API のアクセス許可リンクを使用して、必要なアプリケーション のアクセス許可 を定義していることを確認します。
  7. [証明書 & シークレット] に移動し、[証明書] と [証明書のアップロード] をクリックし、証明書の.cerファイルを選択して追加します。
  8. [ 管理者の同意の付与] を クリックして、追加されたアクセス許可に同意します。

PnP PowerShell を使用した Entra アプリケーションの作成

PnP PowerShell を使用して Entra アプリケーションを作成することは本当に簡単になります。 Register-PnPAzureADApp コマンドレットは、新しい Entra アプリケーションを作成し、CurrentUser 証明書ストアの Personal ノード (= My) 内に新しい自己署名証明書を作成し、その証明書を作成された Entra アプリケーションとフックアップします。 最後に、適切なアクセス許可が構成され、これらのアクセス許可に同意するように求められます。

重要

以下の手順でエラーが発生した場合は、必要なアクセス許可がない可能性があります。 テナント/Entra 管理者にお問い合わせください。

# Before you use this!! 
#  - Remove/update the application/delegated permissions depending on your needs
#  - Also update the Tenant and Username properties to match your environment.
#
# If you prefer to have a password set to secure the created PFX file then add below parameter
# -CertificatePassword (ConvertTo-SecureString -String "password" -AsPlainText -Force)
#
# See https://pnp.github.io/powershell/cmdlets/Register-PnPAzureADApp.html for more options
#
Register-PnPAzureADApp -ApplicationName Microsoft365AssessmentToolForAlerts `
                       -Tenant contoso.onmicrosoft.com `
                       -Store CurrentUser `
                       -GraphApplicationPermissions "Sites.Read.All" `
                       -SharePointApplicationPermissions "Sites.FullControl.All" `
                       -GraphDelegatePermissions "Sites.Read.All", "User.Read" `
                       -SharePointDelegatePermissions "AllSites.FullControl" `
                       -Username "joe@contoso.onmicrosoft.com" `
                       -Interactive

注:

contoso.onmicrosoft.comを Entra テナント名に置き換え、joe@contoso.onmicrosoft.comを Entra 管理者 (またはグローバル管理者) のユーザー ID に置き換えます。 Entra テナント名が不明な場合は、https://entra.microsoft.com/#view/Microsoft_AAD_IAM/TenantOverview.ReactViewに移動し、プライマリ ドメインの値をチェックします。

上記のコマンドで Enter キーを押すと、サインインするように求められます。 Username パラメーターに指定したユーザーを使用してサインインする必要があります。 完了すると、Entra アプリケーションが作成されて構成され、その後、作成がすべてのシステムに確実に反映されるまで 60 秒待ちます。 最後の手順は、管理者の同意フローです。指定した管理者ユーザーでサインインするように再度求められ、その後、アプリケーションに付与されているアクセス許可を示す同意ダイアログが表示されます。 同意フローを完了するには、 Accept キーを押します。 結果の出力では、いくつかの重要な情報を取得します。

Pfx file               : D:\assessment\Microsoft365AssessmentTool.pfx
Cer file               : D:\assessment\Microsoft365AssessmentTool.cer
AzureAppId/ClientId    : 95610f5d-729a-4cd1-9ad7-1fa9052e50dd
Certificate Thumbprint : 165CCE93E08FD3CD85B7B25D5E91C05B1D1E49FE

Register-PnPAzureADAppを実行すると、Entra アプリケーションを作成して構成するだけでなく、アプリケーションのアクセス許可フローの証明書も作成しました。 この証明書は、個人用ノードの下にある現在のユーザーの証明書ストアに追加されています。 コマンド ラインで certmgr を使用して、ローカル ユーザーの証明書ストアを開くことができます。

注:

証明書は、ファイル システム上の PFX ファイルと cer ファイルとしてもエクスポートされます。証明書ストアから証明書を使用する方が簡単なので、これらのエクスポートされたファイルを自由に削除してください。

PnP PowerShell でこのプリンシパルを使用する

PnP PowerShell でこの Entra ID アプリ専用プリンシパルを使用する場合は、PnP PowerShell モジュールをインストールした後、PnP PowerShell でサポートされている非対話型認証を使用して SharePoint Online 環境に接続できます。

Connect-PnPOnline [yourtenant].sharepoint.com -ClientId <client id of your Entra ID Application Registration> -Tenant <tenant>.onmicrosoft.com -CertificatePath <path to your .pfx certificate> 

# or

Connect-PnPOnline [yourtenant].sharepoint.com -ClientId <client id of your Entra ID Application Registration> -Tenant <tenant>.onmicrosoft.com -Thumbprint <thumbprint that can be found in the certificate> 

これにより、このアプリ専用証明信頼を使用して、SharePoint Online 環境に対して PnP PowerShell を通して操作を実行できるようになります。

注:

PnP PowerShell はオープン ソース ソリューションであり、アクティブなコミュニティでサポートが提供されています。 Microsoft からのオープン ソース ツールのサポート SLA はありません。

CSOM アプリケーションでこのプリンシパルを使用する

次の手順に従って、CSOM を使用し、アプリケーション パーミソンで Entra ID を使用して認証する C# コンソール アプリケーションを構築します。

  • c# .net 用の新しいコンソール ベースのソリューションを作成する
  • パッケージ マネージャー コンソールで次のコマンドを実行して、MSAL.NET NuGet パッケージをインストールします。 Install-Package Microsoft.Identity.Client
  • 次のコードをアプリケーションに追加して MSAL を構成し、証明書を使用してアクセス トークンを取得します
using System;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Identity.Client;

namespace YourNamespace
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //Generate Access Token using MSAL
            #region Access Token
            string tenantId = "{Tenant_Id}";
            string clientId = "{Client_Id}";
            string certificatePath = @"{Full Path to the certificate .Pfx file}";
            string certificatePassword = "{Password of the .Pfx file}";
            var siteUrl = new Uri("{SPO Site URL}");

            X509Certificate2 certificate = new X509Certificate2(certificatePath, certificatePassword);

            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
                .WithCertificate(certificate)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                .Build();

            string[] scopes = new string[] { "https://domain.sharepoint.com/.default" };

            AuthenticationResult result = await app.AcquireTokenForClient(scopes).ExecuteAsync();

            var accessToken = result.AccessToken;

            Console.WriteLine($"Access Token: {accessToken}");
            Console.WriteLine();
            Console.WriteLine();
            #endregion

            //Generate SPO Context using the Access token
            #region SPO Context
            using (var context = new ClientContext(siteUrl))
            {
                context.ExecutingWebRequest += async (sender, e) =>
                {
                    // Insert the access token in the request
                    e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
                };

                // Read web properties
                var web = context.Web;
                context.Load(web, w => w.Id, w => w.Title);
                await context.ExecuteQueryAsync();

                Console.WriteLine($"{web.Id} - {web.Title}");
                Console.ReadKey();
            }
            #endregion
        }
    }
}

SharePoint PnP Framework ライブラリを使用して CSOM アプリケーションでこのプリンシパルを使用する

最初の手順では、PnP Framework ライブラリ NuGet パッケージ ( https://www.nuget.org/packages/PnP.Framework) を追加します。

完了したら、次のコードコンストラクトを使用できます。

using PnP.Framework;
using System;

namespace AzureADCertAuth
{
    class Program
    {
        static void Main(string[] args)
        {
            var authManager = new AuthenticationManager("<application id>", "c:\\temp\\mycert.pfx", "<password>", "contoso.onmicrosoft.com");
            using (var cc = authManager.GetContext("https://contoso.sharepoint.com/sites/demo"))
            {
                cc.Load(cc.Web, p => p.Title);
                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
            };
        }
    }
}

注:

PnP Framework は、アクティブなコミュニティがサポートを提供するオープンソース ソリューションです。 Microsoft からのオープン ソース ツールのサポート SLA はありません。

PnP PowerShell に依存しない状態で PowerShell スクリプトでこのプリンシパルを使用する

PFX ファイルとパスワードを使用する

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "<Full Path to the Microsoft.Identity.Client.dll file>"
Add-Type -Path "<Full Path to the Microsoft.IdentityModel.Abstractions.dll file>"

#Declare the Variables
$tenantId = "<Tenant_Id>"
$clientId = "<Client_Id>"
$certPath = "<Full Path to the PFX file>"
$certPassword = "<Password of the .pfx certificate>"
$siteUrl = "https://<Domain>.sharepoint.com/sites/<SiteName>"

# Load the certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($certPath, $certPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

# Get the access token using MSAL
$authority = "https://login.microsoftonline.com/$tenantId"
$scope = New-Object System.Collections.Generic.List[string]
$scope.Add("https://<Domain>.sharepoint.com/.default")
$msalApp = [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($clientId).WithAuthority($authority).WithCertificate($cert).Build()
$authResult = $msalApp.AcquireTokenForClient($scope).ExecuteAsync().Result
$accessToken = $authResult.AccessToken

$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

# Attach event handler for Authorization header
$context.add_ExecutingWebRequest({
    param($sender, $e)
    $e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer $accessToken"
})

# Example: Load Web Title
$web = $context.Web
$context.Load($web)
$context.ExecuteQuery()
 
Write-Host "Site Title:" $web.Title -ForegroundColor Green

拇印を使用して、ユーザーの証明書ストアから証明書を読み込む

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "<Full Path to the Microsoft.Identity.Client.dll file>"
Add-Type -Path "<Full Path to the Microsoft.IdentityModel.Abstractions.dll file>"

$tenantId = "<Tenant_Id>"
$clientId = "<Client_Id>"
$thumbprint = "<Thumbprint value>"
$siteUrl = "https://<Domain>.sharepoint.com/sites/<SiteName>"

# Load the certificate from the CurrentUser\My store
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", "CurrentUser")
$store.Open("ReadOnly")
$cert = $store.Certificates | Where-Object { $_.Thumbprint -eq $thumbprint }
$store.Close()

if (-not $cert) {
    Write-Error "Certificate with thumbprint $thumbprint not found."
    return
}

# Get the access token using MSAL
$authority = "https://login.microsoftonline.com/$tenantId"
$scope = New-Object System.Collections.Generic.List[string]
$scope.Add("https://<Domain>.sharepoint.com/.default")
$msalApp = [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($clientId).WithAuthority($authority).WithCertificate($cert).Build()
$authResult = $msalApp.AcquireTokenForClient($scope).ExecuteAsync().Result
$accessToken = $authResult.AccessToken

# Output the token
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

# Attach event handler for Authorization header
$context.add_ExecutingWebRequest({
    param($sender, $e)
    $e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer $accessToken"
})

# Example: Load Web Title
$web = $context.Web
$context.Load($web)
$context.ExecuteQuery()

Write-Host "Site Title:" $web.Title -ForegroundColor Green

FAQ

Azure AD アプリのアプリ専用アクセスを実現するために、証明書以外の方法を使用できますか?

いいえ、他のすべてのオプションは SharePoint Online によってブロックされ、アクセス拒否メッセージが表示されます。