通过 Entra ID 应用程序权限授予访问权限

使用 SharePoint Online 时,可以在 Entra ID 中定义应用程序,这些应用程序可以被授予对 SharePoint 的权限,也可以被授予对 Microsoft 365 中所有其他服务的权限。 此模型是首选模型,如果你使用的是 SharePoint Online,如果你在本地使用 SharePoint,则必须通过基于 Azure ACS 使用 SharePoint Only 模型,如此处所述。

设置 Entra ID 应用以仅访问应用

在 Entra ID 中,在执行仅应用操作时,必须使用证书请求访问 SharePoint CSOM/REST API:任何拥有证书及其私钥的人员均可使用该应用以及授予应用的权限。 下面逐步介绍了如何设置此模型。

使用 Entra 门户创建 Entra 应用程序

如果要手动创建 Entra 应用程序,请按照以下步骤创建和配置 Entra 应用程序:

  1. 导航到 Entra 门户并单击“应用程序”,然后单击左侧导航中的“应用注册”
  2. 单击 “新建注册 ”页
  3. 为 Entra 应用程序 (提供名称,例如 Microsoft365AssessmentToolForWorkflow)
  4. 选择公共 客户端/本机 (移动 & 桌面) ,然后输入 http://localhost 作为重定向 URI
  5. 单击“注册”,将创建并打开 Entra 应用程序
  6. 确保已通过左侧导航栏的 API 权限 链接定义了所需的应用程序权限
  7. 转到 “证书 & 机密”,单击“ 证书” 和 “上传证书”,选取证书的.cer文件并添加它。
  8. 点击授予 管理员同意 ...以同意添加的权限

使用 PnP PowerShell 创建 Entra 应用程序

使用 PnP PowerShell,创建 Entra 应用程序变得非常简单。 Register-PnPAzureADApp cmdlet 将创建一个新的Entra应用程序,将在个人节点 (= CurrentUser 证书存储的我的) 中创建一个新的自签名证书,并将该证书与创建的 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 秒以确保创建已在所有系统中传播。 最后一步是管理员同意流:系统将再次提示你使用指定的管理员用户登录,然后是显示授予应用程序的权限的同意对话框。 按 “接受” 以完成同意流。 在生成的输出中,你将获得一些关键信息:

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 使用此主体

如果要将此 Entra ID 仅限应用主体与 PnP PowerShell 配合使用,请在安装 PnP PowerShell 模块后,使用 PnP PowerShell 支持的非交互式身份验证连接到 SharePoint Online 环境。

重要

Sites.ReadWrite.All 的计划截止日期为 2027 年 1 月 31 日。 在该日期之后,在租户应用程序目录中添加或更新包或 Tenant-Wide 扩展的仅限应用的工作流将需要对 Office 365 SharePoint Online 资源具有 SharePointTenantSettings.ReadWrite.All 应用程序权限。 Sites.ReadWrite.All 本身将不再足以完成这些操作。 有关详细信息,请参阅 为租户应用程序目录操作配置仅应用权限。

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> 

现在可以通过 PnP PowerShell 使用此证书“仅应用”信任,对 SharePoint Online 环境执行操作。

注意

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
        }
    }
}

在 CSOM 应用程序中使用此主体 使用 SharePoint PnP 框架库

第一步,添加 PnP 框架库 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 框架 是一个开源解决方案,由活跃的社区为其提供支持。 没有用于 Microsoft 开放源代码工具支持的 SLA。

在 PowerShell 脚本中使用此主体,但不依赖于 PnP 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

常见问题

除了使用证书以外,还能使用其他方法对我的 Azure AD 应用实现仅限应用访问吗?

不能,其他所有选项都已被 SharePoint Online 屏蔽,并会导致生成“访问遭拒”消息。