Reputation: 1295
Just starting to work with SharePoint and Microsoft authentication and trying to get a SharePoint List into a JavaScript App. From Microsoft documentation, I need to use the following:
GET https://{site_url}/_api/web/lists/GetByTitle('List Title')
Authorization: "Bearer " + accessToken
Accept: "application/json;odata=verbose"
Have searched everywhere to find an definitive answer to how to obtain this accessToken. All the documentation I can find from Microsoft seem to be out of date. Does anyone know the current method to obtain an accessToken?
Upvotes: 37
Views: 135158
Reputation: 51
this work for me!
from here : https://learn.microsoft.com/en-us/graph/auth-v2-service?tabs=curl
curl --location --request POST
'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'
--header 'Content-Type: application/x-www-form-urlencoded'
--data-urlencode 'client_id=535fb089-9ff3-47b6-9bfb-4f1264799865'
--data-urlencode 'scope=https://graph.microsoft.com/.default'
--data-urlencode 'client_secret=qWgdYAmab0YSkuL1qKv5bPX'
--data-urlencode 'grant_type=client_credentials'
Upvotes: 0
Reputation: 503
If you just need to log in with username/password and call REST API, for example, to download a file, these are the steps you need to do..
You can ask directly for scope to access your SharePoint, no need to use refresh token to get new access token, as described in the first answer - thank God, for that answer.
curl --location --request GET 'https://login.microsoftonline.com/[TENANT ID]/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=[AAD APPLICATION CLIENT ID]' \
--data-urlencode 'scope=https://[YOUR DOMAIN].sharepoint.com/Sites.Read.All' \
--data-urlencode 'username=[USER THAT HAS ACCESS TO THE SITE]' \
--data-urlencode 'password=[PASSWORD OF THAT USER]' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'client_secret=[AAD APPLICATION CLIENT SECRET]'
curl --location 'https://[YOUR DOMAIN].sharepoint.com/sites/_api/web/lists/GetByTitle('\''Documents'\'')/files' \
--header 'Authorization: Bearer [ACCESS TOKEN FROM PREVIOUS STEP]'
Remember to add Graph API permission Sites.Read.All to the AAD application. There is also SharePoint permission AllSites.Read, not sure if they are the same thing but I use the first one.
Upvotes: 1
Reputation: 1
export const pca = new PublicClientApplication(msalConfig);
// Create an Axios instance
export const sharepointApiCall = axios.create({ baseURL: `${BASE_URL}/_api` });
// MSAL.js v2 exposes several account APIs, logic to determine which account to use is the responsibility of the developer
const account = pca.getAllAccounts()[0];
// Define your access token request configuration
const accessTokenRequest = {
//note: leave this scopes for possible future extension - ms has no docs for the names
// scopes: [
// 'openid',
// 'profile',
// 'email',
// 'allsites.fullcontrol',
// 'allsites.manage',
// 'allsites.read',
// 'allsites.write',
// 'sites.fullcontrol.all',
// 'sites.manage.all',
// 'sites.read.all',
// 'sites.readwrite.all',
// 'user.read',
// 'user.read.all',
// ],
scopes: [`${tenantName}/.default`],
// other token request options
account,
redirectUri: 'http://localhost:3001',
};
// Add an Axios interceptor
sharepointApiCall.interceptors.request.use(async (config) => {
try {
const accessTokenResponse = await pca.acquireTokenSilent(accessTokenRequest);
const accessToken = accessTokenResponse.accessToken;
// Add the token to the request headers
config.headers['Authorization'] = `Bearer ${accessToken}`;
return config;
} catch (error) {
console.error('Error acquiring token:', error);
return Promise.reject(error);
}
});
that scopes: [tenant] is the @kadis solution which works,
token is refreshed and cashed automatically so there is no need to have fancy intercepting - but with this you can more easily call rest API of sharepoint for example with react query and if the error occurs use useMsal to login/logout
hope that helps to anyone in future
Upvotes: 0
Reputation: 346
There is not much documentation for SP API, but it still works. You may follow documentation to get token for Graph API by whatever type of authentication is suitable for your scenario, but instead of passing scopes for Graph API (which is "https://graph.microsoft.com/.default"), you should pass scopes for Sharepoint API which is "https://{your tenant name}.sharepoint.com/.default"
".default" will provide you the access with all permissions which was assigned in Azure AD - so also make sure, that Azure admin has granted you required API permissions for SharePoint API.
This will also work for MSAL.
Upvotes: 3
Reputation: 1350
To call SharePoint specific APIs you need to get a SPO specific access token. You can "swap" an regular MS Graph refresh token for an SPO specific token by doing the following:
POST https://login.microsoftonline.com/{{tenantName}}/oauth2/v2.0/token
With the following form data:
client_id=<APP ID>
client_secret=<APP SECRET>
refresh_token=<REFRESH TOKEN FROM ABOVE>
grant_type=refresh_token
scope=https://<YOUR TENANT NAME>.sharepoint.com/Sites.Read.All
You must ensure your app is registered with the correct permissions. In the case above the app must have Sites.Read.All for example.
Upvotes: 38
Reputation: 3655
You could refer to this article to get access token:
Post https://accounts.accesscontrol.windows.net/<Tenant ID>/tokens/OAuth/2
Body:
grant_type client_credentials
client_id <Client ID>
client_secret <Client Secret>
resource 00000003-0000-0ff1-ce00-000000000000/<tenant>.sharepoint.com@<Tenant ID>
My test result:
Upvotes: 11