Yes, it is possible to use the SharePoint REST API with an app-only token for your purpose, but there are specific configurations and permissions that must be in place to avoid the "Unsupported app only token" error.
Steps to Access SharePoint REST API Using Azure AD App:
- Ensure Correct Permissions: Make sure that your Azure AD app has been granted the
Sites.FullControl.Allpermission. This permission allows the app to have full control over all site collections without a signed-in user. - Grant Admin Consent: After assigning the permissions, ensure that admin consent is granted for the permissions. This is crucial for app-only access.
- Acquire Access Token: Use the client ID and client secret to acquire an access token. Make sure you are requesting the token for the SharePoint resource. The token request should look something like this:
POST https://accounts.accesscontrol.windows.net/{tenant_id}/tokens/OAuth/2 Content-Type: application/x-www-form-urlencoded grant_type=client_credentials &client_id={client_id} &client_secret={client_secret} &resource=https://{your_tenant}.sharepoint.com/ - Call the SharePoint REST API: Once you have the access token, include it in the Authorization header when making requests to the SharePoint REST API. For example:
GET https://{your_tenant}.sharepoint.com/_api/web/sitegroups Authorization: Bearer {access_token}
Common Endpoints to Use:
-
/_api/web/sitegroupsto list all site groups. -
/_api/web/roleassignmentsto show role assignments for groups and users. -
/_api/web/roleassignments?$expand=Member,RoleDefinitionBindingsto get detailed permissions.
Troubleshooting Tips:
- If you still encounter the "Unsupported app only token" error, double-check that the permissions are correctly set and that admin consent has been granted.
- Ensure that the app is not trying to access resources that require user context, as app-only tokens cannot impersonate users.
Alternatives:
If the above approach does not work, consider using Microsoft Graph API for other scenarios, but since you mentioned it does not cover your specific needs, you may need to rely on SharePoint REST API and ensure all permissions are correctly configured.
References: