You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS使用模拟应用Bearer Token连接SharePoint Online及令牌获取

SharePoint Online REST API Bearer Token 获取(Windows环境,特定网站集,非租户管理员)

工作原理

Bearer Token是Azure AD签发的OAuth 2.0访问令牌,用于验证请求者对SPO资源的权限。针对你的需求:

  • 限定特定网站集:令牌的权限范围被绑定到目标网站集,而非整个租户。
  • 非租户管理员权限:要么使用当前Windows用户的现有网站集权限(无需管理员介入),要么由目标网站集的管理员为应用授予网站集级权限(无需租户全局管理员)。
  • 优先REST API:所有获取方式都基于标准OAuth 2.0请求,或调用封装了REST逻辑的工具库。

方法1:Windows用户身份(PowerShell快速实现)

直接使用当前登录的Windows用户身份获取令牌,继承该用户在目标网站集的权限,无需额外授权:

  1. 安装MSAL PowerShell模块(Windows环境下):
Install-Module -Name MSAL.PS -Scope CurrentUser -Force
  1. 执行命令获取令牌:
# 替换为你的租户和网站集信息
$tenantName = "your-tenant"
$targetSiteUrl = "https://$tenantName.sharepoint.com/sites/your-target-site"

# SPO内置客户端ID,专门用于用户身份访问
$clientId = "d3590ed6-52b3-4102-aeff-aad2292ab01c"

# 获取令牌(自动弹出内嵌浏览器完成登录,若当前用户未关联Azure AD则需手动输入账号)
$tokenResult = Get-MsalToken -ClientId $clientId -Scope "$targetSiteUrl/.default" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -UseEmbeddedWebView

# 提取Bearer Token
$bearerToken = $tokenResult.AccessToken

使用时,在SPO REST请求头中添加:Authorization: Bearer $bearerToken


方法2:应用身份(无交互,网站集级权限)

适合服务脚本或无交互场景,需由目标网站集管理员完成前置配置(无需租户管理员):

前置配置(网站集管理员操作)

  1. 访问目标网站集的应用注册页面:https://<tenant>.sharepoint.com/sites/<target-site>/_layouts/15/appregnew.aspx
    • 生成Client ID和Client Secret,填写标题、域(填localhost)、重定向URI(填https://localhost),点击创建。
  2. 访问应用权限授予页面:https://<tenant>.sharepoint.com/sites/<target-site>/_layouts/15/appinv.aspx
    • 输入刚才的Client ID查找应用,在权限请求XML中填入网站集级权限(示例为只读,可按需修改Right为Write/FullControl):
    <AppPermissionRequests AllowAppOnlyPolicy="true">
      <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
    </AppPermissionRequests>
    
    • 点击创建,网站集管理员确认授权即可。

Windows环境下PowerShell获取令牌

# 替换为你的信息
$tenantName = "your-tenant"
$targetSiteUrl = "https://$tenantName.sharepoint.com/sites/your-target-site"
$clientId = "your-app-client-id"
$clientSecret = "your-app-client-secret"

# 构建令牌请求
$tokenEndpoint = "https://accounts.accesscontrol.windows.net/$tenantName.onmicrosoft.com/tokens/OAuth/2"
$requestBody = @{
    grant_type    = "client_credentials"
    client_id     = "$clientId@$tenantName.onmicrosoft.com"
    client_secret = $clientSecret
    resource      = "$targetSiteUrl@$tenantName.onmicrosoft.com"
}

# 发送请求获取令牌
$tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $requestBody
$bearerToken = $tokenResponse.access_token

方法3:C#桌面应用(Windows集成登录)

适合自定义Windows桌面程序,自动使用当前登录用户的身份获取令牌:

  1. 安装NuGet包:Microsoft.Identity.Client
  2. 核心代码:
using Microsoft.Identity.Client;
using System;

class SpoTokenHelper
{
    static void Main(string[] args)
    {
        string tenantName = "your-tenant";
        string targetSiteUrl = $"https://{tenantName}.sharepoint.com/sites/your-target-site";
        string clientId = "d3590ed6-52b3-4102-aeff-aad2292ab01c"; // SPO内置客户端ID

        var pca = PublicClientApplicationBuilder
            .Create(clientId)
            .WithAuthority($"https://login.microsoftonline.com/{tenantName}.onmicrosoft.com")
            .WithRedirectUri("urn:ietf:wg:oauth:2.0:oob")
            .Build();

        var scopes = new[] { $"{targetSiteUrl}/.default" };
        var authResult = pca.AcquireTokenInteractive(scopes)
            .WithUseEmbeddedWebView(true)
            .ExecuteAsync()
            .GetAwaiter()
            .GetResult();

        // 输出令牌,用于REST请求
        Console.WriteLine($"Bearer Token: {authResult.AccessToken}");
    }
}

注意事项

  • 令牌有效期默认1小时,过期后需重新获取。
  • 用户身份令牌的权限完全继承当前用户在目标网站集的权限,确保用户本身有访问权限。
  • 应用身份的权限由网站集管理员授予,严格限定在目标网站集内,符合非租户管理员的要求。

内容的提问来源于stack exchange,提问作者AymKdn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:52:29