Getting an authentication token for SharePoint Online allows you to access the SharePoint REST APIs and perform various operations programmatically. The authentication token proves your identity to SharePoint and authorizes your app or script to take specific actions. This article will walk you through the steps to get a SharePoint Online authentication token using various authentication flows.
Overview
SharePoint Online uses OAuth 2.0 authentication protocol to authorize client applications. There are three main authentication flows that can be used to get a token:
- Authorization Code Flow (for web apps)
- Client Credentials Flow (for daemon apps)
- On-Behalf-Of Flow (for service-to-service calls)
The authentication flow you use depends on your application scenario and permission requirements. Once you have the token, you can use it to make calls to SharePoint REST endpoints and perform CRUD operations, search, workflows and more.
Prerequisites
Before you get started, you’ll need to complete the following prerequisites:
- Have an Office 365 tenant with SharePoint Online enabled
- Have Global Admin or SharePoint Admin access
- Register an application in Azure Active Directory to get a client ID and client secret
- Get SharePoint admin consent for the required API permissions
Let’s look at each of these prerequisites in more detail:
Office 365 Tenant
You’ll need access to an Office 365 tenant that has SharePoint Online enabled. If you don’t have an existing O365 tenant, you can get a free developer tenant to test with.
SharePoint Admin Access
To register an app in Azure AD and grant admin consent, you’ll need to have Global Admin or SharePoint Admin privileges in the tenant.
Register Azure AD App
Head over to the Azure Active Directory admin center in the Azure portal and register a new application. This will get you a client ID and client secret which are needed to request tokens.
Grant Admin Consent
For the registered app, you need to grant admin consent to the SharePoint API permissions it requires. This step authorizes the app to call the respective APIs on behalf of the tenant’s users.
Authorization Code Flow
The Authorization Code flow is commonly used for web applications that need to access SharePoint data. It enables interactive sign-in and access token retrieval.
Here are the steps to get a token using this flow:
- Redirect users to the Azure login page for authentication and consent.
- Azure AD authenticates the user and redirects back an authorization code.
- The app uses the auth code to request an access token from Azure AD.
- Azure AD verifies the code and returns an access token.
- Use the access token to call SharePoint Online REST APIs.
To implement this:
- Register an Azure AD app with the API permissions required for SharePoint.
- Call the
/authorize
endpoint, passing the client ID, requested scopes, and the redirect URI. - User signs in and consents.
- Get the auth code from the redirect URI.
- Call
/token
endpoint, passing the client ID, client secret, auth code, and the same redirect URI. - Exchange auth code for an access token.
- Call SharePoint REST APIs using the access token in the Authorization header.
This allows your web app to authenticate users interactively and access SharePoint data on their behalf.
Client Credentials Flow
The Client Credentials flow is used for daemon services, batch jobs, or other server-side processes that need to run without user interaction. This flow only provides application permissions, not delegated user permissions.
Here are the steps:
- Register an Azure AD application with application permissions to SharePoint.
- Grant admin consent to the required permissions.
- From your app, call the
/token
endpoint passing the client ID, client secret, and resource URL. - Azure AD validates the app and returns an access token.
- Call the SharePoint REST APIs using the token.
To implement:
- Register an Azure AD only application with application permissions to SharePoint.
- An admin grants consent to the permissions.
- In your app, call the
/token
endpoint with the following parameters:
- client_id = your app’s client ID
- client_secret = your app’s client secret
- grant_type = client_credentials
- resource = resource URI e.g https://contoso.sharepoint.com
This flow allows daemon apps to access SharePoint APIs without a logged in user.
On-Behalf-Of Flow
The On-Behalf-Of flow is used for service-to-service authentication between a client app, a middleware API, and SharePoint. It propagates user identity and permissions through the middleware to SharePoint.
Here are the steps:
- User authenticates to client app and receives access token A.
- Client app calls middleware API, sending token A.
- Middleware API needs to call SharePoint so it requests token B on behalf of that user.
- SharePoint validates token B and the user’s identity.
- Middleware can now call SharePoint APIs using token B.
To implement this:
- User signs in to client app using Authorization Code flow.
- Client app calls middleware sending the user’s access token A.
- Middleware requests a new token B to SharePoint using the On-Behalf-Of flow:
- grant_type = urn:ietf:params:oauth:grant-type:jwt-bearer
- client_id = middleware app’s client ID
- client_secret = middleware app’s client secret
- assertion = user’s access token A
- resource = SharePoint resource URI
- requested_token_use = on_behalf_of
This allows the middleware to propagate authenticated user identities and access SharePoint using their permissions.
Code Examples
Here are some code examples in different languages for acquiring a SharePoint Online access token using the OAuth2 flows:
C#
“`csharp
// Authorization Code Flow
string authorizationUrl = $”{authEndpoint}/authorize?client_id={clientId}&response_type=code&redirect_uri={redirectUri}&scope={scopes}”;
// Get auth code from redirect url
string authCode = Request.QueryString[“code”];
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Basic”, encodedClientCredentials);
var tokenRequestBody = new {
grant_type = “authorization_code”,
code = authCode,
redirect_uri = redirectUri,
client_id = clientId,
client_secret = clientSecret
};
HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, $”{authEndpoint}/token”);
tokenRequest.Content = new FormUrlEncodedContent(tokenRequestBody);
HttpResponseMessage tokenResponse = await client.SendAsync(tokenRequest);
string json = await tokenResponse.Content.ReadAsStringAsync();
// Extract access token
JObject responseObject = JObject.Parse(json);
string accessToken = responseObject[“access_token”].ToString();
// Client Credentials Flow
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Basic”, encodedClientCredentials);
var clientCredentialsBody = new {
client_id = clientId,
client_secret = clientSecret,
grant_type = “client_credentials”,
resource = resourceUri
};
tokenRequest = new HttpRequestMessage(HttpMethod.Post,$”{authEndpoint}/token”);
tokenRequest.Content = new FormUrlEncodedContent(clientCredentialsBody);
tokenResponse = await client.SendAsync(tokenRequest);
json = await tokenResponse.Content.ReadAsStringAsync();
// Extract access token
responseObject = JObject.Parse(json);
accessToken = responseObject[“access_token”].ToString();
“`
Java
“`java
// Authorization Code Flow
String authorizeUrl = authEndpoint + “/authorize?client_id=” + clientId +”&response_type=code&redirect_uri=” + redirectUri + “&scope=” + scopes;
// Get auth code from redirect
String authCode = request.getParameter(“code”);
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse(“application/x-www-form-urlencoded”);
RequestBody body = RequestBody.create(mediaType, “client_id=” + clientId + “&client_secret=” + clientSecret + “&grant_type=authorization_code” + “&code=” + authCode + “&redirect_uri=” + redirectUri);
Request request = new Request.Builder()
.url(authEndpoint + “/token”)
.post(body)
.addHeader(“content-type”, “application/x-www-form-urlencoded”)
.build();
Response response = client.newCall(request).execute();
String json = response.body().string();
// Extract access token
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(json).getAsJsonObject();
String accessToken = obj.get(“access_token”).getAsString();
// Client Credentials Flow
MediaType mediaType = MediaType.parse(“application/x-www-form-urlencoded”);
RequestBody body = RequestBody.create(mediaType, “client_id=” + clientId + “&client_secret=” + clientSecret + “&grant_type=client_credentials&resource=” + resourceUri);
Request request = new Request.Builder()
.url(authEndpoint + “/token”)
.post(body)
.addHeader(“content-type”, “application/x-www-form-urlencoded”)
.build();
Response response = client.newCall(request).execute();
// Extract access token
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(response.body().string()).getAsJsonObject();
accessToken = obj.get(“access_token”).getAsString();
“`
Python
“`python
import requests
import urllib
# Authorization Code Flow
params = urllib.parse.urlencode({
‘client_id’: client_id,
‘response_type’: ‘code’,
‘redirect_uri’: redirect_uri,
‘scope’: scopes
})
authorize_url = ‘{0}/authorize?{1}’.format(auth_endpoint, params)
# Get auth code from redirect
auth_code = request.args.get(‘code’)
headers = {
‘content-type’: ‘application/x-www-form-urlencoded’
}
data = {
‘grant_type’: ‘authorization_code’,
‘code’: auth_code,
‘redirect_uri’: redirect_uri,
‘client_id’: client_id,
‘client_secret’: client_secret
}
token_response = requests.post(‘{0}/token’.format(auth_endpoint), data=data, headers=headers)
access_token = token_response.json().get(‘access_token’)
# Client Credentials Flow
headers = {
‘content-type’: ‘application/x-www-form-urlencoded’
}
data = {
‘grant_type’: ‘client_credentials’,
‘client_id’: client_id,
‘client_secret’: client_secret,
‘resource’: resource_uri
}
token_response = requests.post(‘{0}/token’.format(auth_endpoint), data=data, headers=headers)
access_token = token_response.json().get(‘access_token’)
“`
Troubleshooting
Here are some common issues faced when getting a SharePoint Online authentication token and how to resolve them:
Error “Unsupported Grant Type”
This error occurs if an invalid grant_type parameter is passed in the token request. Make sure you are using “authorization_code” for auth code flow, “client_credentials” for client credentials flow etc.
Error “Unauthorized”
This 401 unauthorized error happens if the client ID, client secret or auth code are invalid. Verify you are passing the right credentials to Azure AD.
“Invalid Scope” Error
This occurs when your Azure AD app doesn’t have admin consent granted for the SharePoint API permissions. Run the admin consent flow for the required scopes.
Redirect URI Mismatch
The redirect URI passed to Azure AD must exactly match the one registered in your app. If not, you will get an error due to mismatch.
Conclusion
Here are the key takeaways from this guide on getting SharePoint Online access tokens:
- OAuth 2.0 protocols are used to authenticate and authorize access to SharePoint data.
- The Authorization Code flow is commonly used for web apps that need user sign-in.
- The Client Credentials flow allows daemon services to access APIs without a user.
- The On-Behalf-Of flow propagates user identity and permissions through middleware.
- Register an Azure AD app and grant admin consent to use the APIs.
- Use the appropriate auth endpoints and parameters to request an access token.
- Pass the access token in the Authorization header when calling SharePoint REST APIs.
With the ability to programmatically get SharePoint access tokens, you can build custom applications and integrate with SharePoint in powerful ways.