Introduction
SharePoint Online access token is required to perform any CRUD operations. We can use this token to authenticate and access SharePoint REST APIs.
Step 1. Register the app on SharePoint
To register the app, go to the /_layouts/appregnew.aspx page of your site collection. Below is an example.
Example: https://mysite.sharepoint.com/sites/demo/_layouts/15/appregnew.aspx
In the above link, the demo is the site collection where we are registering the app.
- Client Id: Click on the Generate button on Client Id
- Client Secret: Click on the Generate button on the Client secret
- Title: Provide the name of your app
- App Domain: Copy and paste the example 'www.contoso.com' (for our purpose, this will work)
- Redirect URI: Copy and paste the example 'https://www.contoso.com/default.aspx' (for our purpose, this will work)
Click on Create and copy and save the generated Client Id & Client Secret in Notepad, we will use this in our code.
Step 2. Install the above registered app on SharePoint Site collection
That's it. Our app is now installed in our site collection.
You can verify your installed app using /_layouts/15/appprincipals.aspx page
Example: https://mysite.sharepoint.com/sites/demo/_layouts/15/appprincipals.aspx
Note: This app will be valid for 1 Year only, after 1 year Client ID & Client secret will be expired and we will have register new App following the same steps.
Step 3. Get SharePoint Online Access Token using .Net Core
Prerequisites
ClientId |
Client ID of SharePoint App registered on Site Collection |
ClientSecret |
Client Secret of SharePoint App registered on Site Collection |
Tenant |
Tenant ID of you SharePoint Site Collection |
Create a class in your project with name AuthenticationManager.cs, and copy and paste the code below.
public static class AuthenticationManager {
private static readonly HttpClient httpClient = new HttpClient();
// SharePoint Tenant ID
private static string tenantID = Environment.GetEnvironmentVariable("Tenant");
// Registered SharePoint App ID
private static string clientId = Environment.GetEnvironmentVariable("ClientId");
// Registered SharePoint App Secret
private static string clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
public static async Task <string> AcquireTokenAsync(Uri web) {
try {
string authURL = "https://accounts.accesscontrol.windows.net/{tenantID}/tokens/OAuth/2";
var body = "grant_type=client_credentials" +
$ "&resource=00000003-0000-0ff1-ce00-000000000000/{web.DnsSafeHost}@{tenantID}" +
$ "&client_id={clientId}@{tenantID}" +
$ "&client_secret={clientSecret}";
if (string.IsNullOrEmpty(tenantID)) {
throw new Exception("AcquireTokenAsync:: Tenant not found in configuration");
}
if (string.IsNullOrEmpty(clientId)) {
throw new Exception("AcquireTokenAsync:: clientSecret not found in configuration");
}
if (string.IsNullOrEmpty(clientSecret)) {
throw new Exception("AcquireTokenAsync:: clientSecret not found in configuration");
}
using(var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")) {
var result = await httpClient.PostAsync(authURL, stringContent)
.ContinueWith((response) => {
return response.Result.Content.ReadAsStringAsync().Result;
})
.ConfigureAwait(false);
var tokenResult = JsonSerializer.Deserialize < JsonElement > (result);
var token = string.Empty;
try {
token = tokenResult.GetProperty("access_token").GetString();
} catch (Exception _ex) {
string _token = JsonSerializer.Serialize(tokenResult);
throw new Exception("AcquireTokenAsync:: access_token not found in tokenResult, tokenResult --> " + _token);
}
return token;
}
} catch (Exception ex) {
throw ex;
}
}
}
Define the below method in another class and call the AcquireTokenAsync() method of AuthenticationManager.cs.
public async Task <string> GetAccessTokenAsync() {
try {
string siteUrl= "https://mysite.sharepoint.com"
string accessToken = await AuthenticationManager.AcquireTokenAsync(new Uri(siteUrl));
if (accessToken != null) {
return accessToken;
}
return null;
} catch (Exception ex) {
// Log exception
return null;
}
}
AcquireTokenAsync() will return the Access Token as a string.
You can use this token to call SharePoint REST APIs by providing an access token as a Bearer Token.
Conclusion
In this article, we have learned how to register an app on SharePoint site collection and how we can use registered app credentials (Client Id & Client secret) to generate SharePoint online access token in .Net Core.