新手求教:如何获取SharePoint Rest API的有效Access Token?
Hey there! I totally get the frustration with outdated Microsoft docs when you're just starting out with SharePoint and Microsoft authentication—let me break down the current, supported ways to get an access token for your JavaScript app to call the SharePoint REST API.
The old methods (like ADAL.js) are now deprecated, so we'll focus on the modern, supported approaches based on your app type:
1. Standalone Single-Page Apps (SPAs) – Use MSAL.js v2
This is the recommended approach for any standalone JavaScript app (like a React/Vue/Angular app) that needs to access SharePoint on behalf of a logged-in user.
Step-by-Step:
- Register your app in Azure AD:
- Go to the Azure Portal → Azure Active Directory → App Registrations → New Registration.
- Select "Single-page application (SPA)" as the app type, enter your app's redirect URI (e.g.,
http://localhost:3000for local development), and register. - Under API Permissions, add a delegated permission for SharePoint: search for "SharePoint", select permissions like
Sites.Read.AllorSites.ReadWrite.All, then click "Grant admin consent for [Your Tenant]" (required if you want all users to access it without individual consent).
- Install MSAL.js:
npm install @azure/msal-browser - Initialize MSAL and get the token:
import { PublicClientApplication } from '@azure/msal-browser'; // Configure MSAL const msalConfig = { auth: { clientId: 'YOUR_AZURE_AD_APP_CLIENT_ID', authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID', // Or 'https://login.microsoftonline.com/common' for multi-tenant redirectUri: 'YOUR_APP_REDIRECT_URI' } }; const msalInstance = new PublicClientApplication(msalConfig); // Login and acquire token async function getSharePointToken() { // First, check if we have an active account const accounts = msalInstance.getAllAccounts(); let account = accounts[0]; if (!account) { // Redirect or popup login const loginResponse = await msalInstance.loginPopup({ scopes: ['https://YOUR_SITE_URL/.default'] // e.g., 'https://contoso.sharepoint.com/.default' }); account = loginResponse.account; } // Acquire token silently (or popup if silent fails) const tokenResponse = await msalInstance.acquireTokenSilent({ account: account, scopes: ['https://YOUR_SITE_URL/.default'] }); return tokenResponse.accessToken; } // Use the token in your SharePoint REST call async function fetchSharePointList() { const accessToken = await getSharePointToken(); const response = await fetch('https://YOUR_SITE_URL/_api/web/lists/GetByTitle(\'List Title\')', { method: 'GET', headers: { 'Authorization': `Bearer ${accessToken}`, 'Accept': 'application/json;odata=verbose' } }); const data = await response.json(); console.log(data); }
2. SharePoint Framework (SPFx) Apps
If you're building an SPFx web part or extension, you don't need to manually handle MSAL—SPFx provides built-in tools to access SharePoint APIs with automatic token management.
Example using SPFx's SPHttpClient:
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http'; // In your web part's render or onInit method async function getSharePointList() { const response = await this.context.spHttpClient.get( `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/GetByTitle('List Title')`, SPHttpClient.configurations.v1, { headers: { 'Accept': 'application/json;odata=verbose' } } ); const data = await response.json(); console.log(data); }
SPFx automatically handles the access token for you, so you don't need to include the Authorization header manually.
3. Server-Side/Background JavaScript Apps (Node.js) – Client Credentials Flow
If your app needs to access SharePoint without a user logged in (e.g., a Node.js backend service), use the Client Credentials Flow with MSAL Node.
Step-by-Step:
- Register a confidential client app in Azure AD:
- Go to Azure Portal → App Registrations → New Registration.
- Select "Web app/API" (or "Confidential client" in newer portals), enter a redirect URI (can be a dummy one for server-side apps), and register.
- Under Certificates & Secrets, create a new client secret (save this value—you'll only see it once!).
- Under API Permissions, add an application permission for SharePoint (e.g.,
Sites.Read.All), then grant admin consent.
- Install MSAL Node:
npm install @azure/msal-node - Acquire token using client credentials:
const { ConfidentialClientApplication } = require('@azure/msal-node'); const config = { auth: { clientId: 'YOUR_AZURE_AD_APP_CLIENT_ID', clientSecret: 'YOUR_AZURE_AD_APP_CLIENT_SECRET', authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID' } }; const cca = new ConfidentialClientApplication(config); async function getSharePointToken() { const tokenRequest = { scopes: ['https://YOUR_SITE_URL/.default'] // e.g., 'https://contoso.sharepoint.com/.default' }; const response = await cca.acquireTokenByClientCredential(tokenRequest); return response.accessToken; } // Use the token in your REST call async function fetchList() { const token = await getSharePointToken(); const response = await fetch('https://YOUR_SITE_URL/_api/web/lists/GetByTitle(\'List Title\')', { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json;odata=verbose' } }); const data = await response.json(); console.log(data); }
Key Notes to Remember:
- Permission Types: Use delegated permissions for user-facing apps, application permissions for background services.
- Admin Consent: Most permissions require admin consent to work across your tenant—don't forget this step!
- Token Validation: You can check your token's validity and claims using jwt.ms (just paste the token there) to ensure the
aud(audience) matches your SharePoint site URL and thescp/rolesinclude your required permissions.
内容的提问来源于stack exchange,提问作者L H

