I'm trying to read from my share point and I got the error System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.' my code. Can any one give me idea why I got this error ?
static async Task Main(string[] args)
{
string siteURL = "MyURL";
string clientId = "MYCLIENTID"; // Get client ID from Azure AD
string secrete = "MYSECRET";// Get Client Secrete from Azure AD
string tenantId = "MY";
var scopes = new string[] { "https://MYURL/.default" };
var accessToken = await GetAuthenticatedClientAccessToken(clientId, secrete, scopes, tenantId);
var clientContext = GetClientContext(siteURL, accessToken);
Web web = clientContext.Web;
Console.WriteLine(web.Title);
Console.ReadKey();
}
internal static async Task<string> GetAuthenticatedClientAccessToken(string clientId, string secrete, string[] scopes, string tenantId)
{
IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(secrete)
.WithTenantId(tenantId)
.Build();
AuthenticationResult authResult = await clientApp.AcquireTokenForClient(scopes).ExecuteAsync();
string accessToken = authResult.AccessToken;
return accessToken;
}
public static ClientContext GetClientContext(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
};
return clientContext;
}
}