Introduction

This article will cover, How to consume Sharepoint online CSOM (REST API) operation using .NET Core 3.1 framework into a console application.
The topic needs to cover here:
  1. Create Azure AD Instance with Delegate Permission.
  2. Create Console Application and Add Microsoft.SharePointOnline.CSOM Nuget Package.
  3. Add Authentication Manager Class to generate the access token.
  4. Get Access Token & access SharePoint Online List data
Step 1 - Create Azure AD Instance with Delegate Permission
Note
Users should have access to Azure Active Directory.
  • Login to https://portal.azure.com
  • Search and Select Azure Active Directory
Once the user selects Azure AD, the App registration page will appear.
  1. Select App registrations
  2. Select +New registration
Once the user selects new registration, add below details
  1. Name "spocsom-api", user can add as per project namespace or naming convention guidelines.
  2. Select "Account in this organization (single-tenant)
  3. Click on the Register button
Grant access to SharePoint Online.
  1. Select API Permission
  2. Click to Add Permission
  3. Search and Add SharePoint from Request API Permission
Delegate Permission, It required where user application needs to access data as the signed-in user.
  1. Select Add a Permission
  2. Selection Delegate Permission
  3. Search and Select Sites
  4. Choose "All Site.Read" -> This is not site specific but quite secure , It will just come into use to generate token, not going to grant access to the site to access the content.
  5. Click to "Add Permission"
Grant Admin Consent
Grant permission by admin or user as part of the consent process.
  1. Select "Grant admin consent for default directory and click ok to proceed.
  2. All added api will show granted admin consent on behalf of the user. so it will not prompt for consent.
Allow Public Client Flows
The app is going to collect username and password into plain text, so it should allow to yes.
  1. Select authentication and scroll down till the end
  2. Under advance settings -> select Allow Public client flows -> Select Yes -> Click on Save to Proceed.
Step 2 - Create Console Application and Add Microsoft.SharePointOnline.CSOM Nuget Package
  1. Login to Visual Studio 2019 and Create New Project
  2. Select ConsoleApp (.Net Core) and Ok to proceed.
Install NuGet Package
Select solution and right-click on dependencies and NuGet Packages
Install the below packages:
  1. Microsoft.SharepointOnline.CSOM
  2. Newtonsoft.Json
  3. System.IdentityModel.Token.Jwt
Step 3 - Add Authentication Manager Class to generate the access token
This class helps us to generate access tokens based on application URI, UserName, Password & Azurre AD App Client ID.
Create Auth Manager Class and Copy paste the below codebase:
  1. public class AuthManager : IDisposable
  2. {
  3. private static readonly HttpClient httpClient = new HttpClient();
  4. private const string tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/token";
  5. // Replace with Azure AD Client ID -Generated in above Steps
  6. private const string defaultAADAppId = "Azure Active Director Client ID";
  7. // Token cache handling
  8. private static readonly SemaphoreSlim semaphoreSlimTokens = new SemaphoreSlim(1);
  9. private AutoResetEvent tokenResetEvent = null;
  10. private readonly ConcurrentDictionary<string, string> tokenCache = new ConcurrentDictionary<string, string>();
  11. private bool disposedValue;
  12. internal class TokenWaitInfo
  13. {
  14. public RegisteredWaitHandle Handle = null;
  15. }
  16. public ClientContext GetContext(Uri web, string userPrincipalName, SecureString userPassword)
  17. {
  18. var context = new ClientContext(web);
  19. context.ExecutingWebRequest += (sender, e) =>
  20. {
  21. string accessToken = EnsureAccessTokenAsync(new Uri($"{web.Scheme}://{web.DnsSafeHost}"), userPrincipalName, new System.Net.NetworkCredential(string.Empty, userPassword).Password).GetAwaiter().GetResult();
  22. e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
  23. };
  24. return context;
  25. }
  26. public async Task<string> EnsureAccessTokenAsync(Uri resourceUri, string userPrincipalName, string userPassword)
  27. {
  28. string accessTokenFromCache = TokenFromCache(resourceUri, tokenCache);
  29. if (accessTokenFromCache == null)
  30. {
  31. await semaphoreSlimTokens.WaitAsync().ConfigureAwait(false);
  32. try
  33. {
  34. // No async methods are allowed in a lock section
  35. string accessToken = await AcquireTokenAsync(resourceUri, userPrincipalName, userPassword).ConfigureAwait(false);
  36. Console.WriteLine($"Successfully requested new access token resource {resourceUri.DnsSafeHost} for user {userPrincipalName}");
  37. AddTokenToCache(resourceUri, tokenCache, accessToken);
  38. // Register a thread to invalidate the access token once's it's expired
  39. tokenResetEvent = new AutoResetEvent(false);
  40. TokenWaitInfo wi = new TokenWaitInfo();
  41. wi.Handle = ThreadPool.RegisterWaitForSingleObject(
  42. tokenResetEvent,
  43. async (state, timedOut) =>
  44. {
  45. if (!timedOut)
  46. {
  47. TokenWaitInfo internalWaitToken = (TokenWaitInfo)state;
  48. if (internalWaitToken.Handle != null)
  49. {
  50. internalWaitToken.Handle.Unregister(null);
  51. }
  52. }
  53. else
  54. {
  55. try
  56. {
  57. // Take a lock to ensure no other threads are updating the SharePoint Access token at this time
  58. await semaphoreSlimTokens.WaitAsync().ConfigureAwait(false);
  59. RemoveTokenFromCache(resourceUri, tokenCache);
  60. Console.WriteLine($"Cached token for resource {resourceUri.DnsSafeHost} and user {userPrincipalName} expired");
  61. }
  62. catch (Exception ex)
  63. {
  64. Console.WriteLine($"Something went wrong during cache token invalidation: {ex.Message}");
  65. RemoveTokenFromCache(resourceUri, tokenCache);
  66. }
  67. finally
  68. {
  69. semaphoreSlimTokens.Release();
  70. }
  71. }
  72. },
  73. wi,
  74. (uint)CalculateThreadSleep(accessToken).TotalMilliseconds,
  75. true
  76. );
  77. return accessToken;
  78. }
  79. finally
  80. {
  81. semaphoreSlimTokens.Release();
  82. }
  83. }
  84. else
  85. {
  86. Console.WriteLine($"Returning token from cache for resource {resourceUri.DnsSafeHost} and user {userPrincipalName}");
  87. return accessTokenFromCache;
  88. }
  89. }
  90. public async Task<string> AcquireTokenAsync(Uri resourceUri, string username, string password)
  91. {
  92. string resource = $"{resourceUri.Scheme}://{resourceUri.DnsSafeHost}";
  93. var clientId = defaultAADAppId;
  94. var body = $"resource={resource}&client_id={clientId}&grant_type=password&username={HttpUtility.UrlEncode(username)}&password={HttpUtility.UrlEncode(password)}";
  95. using (var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"))
  96. {
  97. var result = await httpClient.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
  98. {
  99. return response.Result.Content.ReadAsStringAsync().Result;
  100. }).ConfigureAwait(false);
  101. var tokenResult = JsonSerializer.Deserialize<JsonElement>(result);
  102. var token = tokenResult.GetProperty("access_token").GetString();
  103. return token;
  104. }
  105. }
  106. private static string TokenFromCache(Uri web, ConcurrentDictionary<string, string> tokenCache)
  107. {
  108. if (tokenCache.TryGetValue(web.DnsSafeHost, out string accessToken))
  109. {
  110. return accessToken;
  111. }
  112. return null;
  113. }
  114. private static void AddTokenToCache(Uri web, ConcurrentDictionary<string, string> tokenCache, string newAccessToken)
  115. {
  116. if (tokenCache.TryGetValue(web.DnsSafeHost, out string currentAccessToken))
  117. {
  118. tokenCache.TryUpdate(web.DnsSafeHost, newAccessToken, currentAccessToken);
  119. }
  120. else
  121. {
  122. tokenCache.TryAdd(web.DnsSafeHost, newAccessToken);
  123. }
  124. }
  125. private static void RemoveTokenFromCache(Uri web, ConcurrentDictionary<string, string> tokenCache)
  126. {
  127. tokenCache.TryRemove(web.DnsSafeHost, out string currentAccessToken);
  128. }
  129. private static TimeSpan CalculateThreadSleep(string accessToken)
  130. {
  131. var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
  132. var lease = GetAccessTokenLease(token.ValidTo);
  133. lease = TimeSpan.FromSeconds(lease.TotalSeconds - TimeSpan.FromMinutes(5).TotalSeconds > 0 ? lease.TotalSeconds - TimeSpan.FromMinutes(5).TotalSeconds : lease.TotalSeconds);
  134. return lease;
  135. }
  136. private static TimeSpan GetAccessTokenLease(DateTime expiresOn)
  137. {
  138. DateTime now = DateTime.UtcNow;
  139. DateTime expires = expiresOn.Kind == DateTimeKind.Utc ? expiresOn : TimeZoneInfo.ConvertTimeToUtc(expiresOn);
  140. TimeSpan lease = expires - now;
  141. return lease;
  142. }
  143. protected virtual void Dispose(bool disposing)
  144. {
  145. if (!disposedValue)
  146. {
  147. if (disposing)
  148. {
  149. if (tokenResetEvent != null)
  150. {
  151. tokenResetEvent.Set();
  152. tokenResetEvent.Dispose();
  153. }
  154. }
  155. disposedValue = true;
  156. }
  157. }
  158. public void Dispose()
  159. {
  160. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  161. Dispose(disposing: true);
  162. GC.SuppressFinalize(this);
  163. }
  164. }
Step 4 - Get Access Token & access SharePoint Online List data
Get List Data function get data from SharePoint online List and Print out all result based on return data.
  1. static void Main(string[] args)
  2. {
  3. List<Data> getdata = GetListData();
  4. foreach (Data data in getdata)
  5. {
  6. Console.WriteLine("Employee Name " + data.Title);
  7. }
  8. Console.ReadLine();
  9. }
The codebase will invoke the SharePoint online api with help of an access token
  1. public static List<Data> GetListData()
  2. {
  3. const string DataColumn = "ID,Title";
  4. const string DataAPIAllData = "{0}/_api/lists/getbytitle('{1}')/items?$top=10&$select=" + DataColumn + "&$orderby=Modified desc";
  5. try
  6. {
  7. var results = new List<Data>();
  8. string sharepointSiteUrl = Convert.ToString("https://mittal1201.sharepoint.com/sites/CommSiteHub");
  9. if (!string.IsNullOrEmpty(sharepointSiteUrl))
  10. {
  11. string listname = "Employee";
  12. string api = string.Format(DataAPIAllData, sharepointSiteUrl, listname);
  13. if (!string.IsNullOrEmpty(listname))
  14. {
  15. //Invoke REST Call
  16. string response = TokenHelper.GetAPIResponse(api);
  17. if (!String.IsNullOrEmpty(response))
  18. {
  19. JObject jobj = Utility.Deserialize(response);
  20. JArray jarr = (JArray)jobj["d"]["results"];
  21. //Write Response to Output
  22. foreach (JObject j in jarr)
  23. {
  24. Data data = new Data();
  25. data.Title = Convert.ToString(j["Title"]);
  26. results.Add(data);
  27. }
  28. }
  29. return results;
  30. }
  31. else
  32. {
  33. throw new Exception("Custom Message");
  34. }
  35. }
  36. else
  37. {
  38. throw new Exception("Custom Message");
  39. }
  40. }
  41. catch (Exception ex)
  42. {
  43. throw new Exception("Custom Message");
  44. }
  45. }
  46. }
Created a data class with filed title here
  1. public class Data
  2. {
  3. public string Title { get; set; }
  4. }
Create TokenHelper class to get access token based on user credentials and URI. This function helps to get access from AuthManager Class with the provided information.
  1. public static string GetAPIResponse(string url)
  2. {
  3. string response = String.Empty;
  4. try
  5. {
  6. //Call to get AccessToken
  7. string accessToken = GetSharePointAccessToken();
  8. //Call to get the REST API response from Sharepoint
  9. System.Net.HttpWebRequest endpointRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
  10. endpointRequest.Method = "GET";
  11. endpointRequest.Accept = "application/json;odata=verbose";
  12. endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
  13. System.Net.WebResponse webResponse = endpointRequest.GetResponse();
  14. Stream webStream = webResponse.GetResponseStream();
  15. StreamReader responseReader = new StreamReader(webStream);
  16. response = responseReader.ReadToEnd();
  17. return response;
  18. }
  19. catch (Exception ex)
  20. {
  21. throw;
  22. }
  23. }
  24. public static string GetSharePointAccessToken()
  25. {
  26. Uri site = new Uri("https://mittal1201.sharepoint.com/sites/CommSiteHub");
  27. string user = "user email address";
  28. string pwd = "user password";
  29. string result;
  30. using (var authenticationManager = new AuthManager())
  31. {
  32. string accessTokenSP = authenticationManager.AcquireTokenAsync(site, user, pwd).Result;
  33. result = accessTokenSP;
  34. }
  35. return result;
  36. }
Output Window
Execute this solution or press F5.
SharePoint List Screen Shot where data is going to read by a console app
Console Output
Finally, we got output using .NetCore 3.1 console app instead of .NetStandard framework.
I hope you enjoyed and learned something new in this article.