Skip to content

Instantly share code, notes, and snippets.

@furkankaracan
Created October 28, 2022 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furkankaracan/d10a6c462bf834ec7133c8d52247a691 to your computer and use it in GitHub Desktop.
Save furkankaracan/d10a6c462bf834ec7133c8d52247a691 to your computer and use it in GitHub Desktop.
private static void GetAccessToken()
{
try
{
SHAREPOINT_TOKEN = string.Empty;
WebRequest request = WebRequest.Create("https://accounts.accesscontrol.windows.net/" + TENANT_ID + "/tokens/OAuth/2");
request.Method = "POST";
string postData = "grant_type=client_credentials" +
"&client_id=" + WebUtility.UrlEncode(CLIENT_ID + "@" + TENANT_ID) +
"&client_secret=" + WebUtility.UrlEncode(CLIENT_SECRET) +
"&resource=" + WebUtility.UrlEncode(SHAREPOINT_RESOURCE_ID + "/" + SHAREPOINT_DOMAIN + "@" + TENANT_ID);
_logger.LogInformation($"postData: {postData} ");
_logger.LogInformation("GetBytes: postData ");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
_logger.LogInformation("GetRequestStream: request ");
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
_logger.LogInformation("Calling: request.GetResponse ");
using WebResponse response = request.GetResponse();
_logger.LogInformation("GetResponseStream: response ");
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
_logger.LogInformation($"responseFromServer: {responseFromServer} ");
const string accessToken = "access_token\":\"";
int clientIndex = responseFromServer.IndexOf(accessToken, StringComparison.Ordinal);
int accessTokenIndex = clientIndex + accessToken.Length;
SHAREPOINT_TOKEN = responseFromServer.Substring(accessTokenIndex, (responseFromServer.Length - accessTokenIndex - 2));
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment