I am trying to connect the SharePoint site with client id and secret but getting 401 Unauthorized
error while hitting the executequery()
method.
While doing app registrations, both Microsoft Graph and SharePoint API permissions with full site control have been given including trusted the app through appinv.aspx
. Still getting 401 Unauthorized
error.
Since ACS is retiring, do we need to follow any other permissions for share point level site access. The same execute query is working fine for client id, certificate combination. But not working for client id and secret.
static void Main(string[] args)
{
var authManager = new AuthenticationManager("***************************", "C:\\Program Files\\OpenSSL-Win64\\bin\\certificate.pfx", "*******", "********.onmicrosoft");
using (var cc = authManager.GetContext("https://****.sharepoint/sites/****"))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
ListCollection listCollection = cc.Web.Lists;
cc.ExecuteQuery(); // this is working fine
}
;
// Replace with your SharePoint Online details
string siteUrl = "****************************";
string tenantId = "***************************";
string clientId = "********************************";
string clientSecret = "******************************"; // App secret
try
{
using (var context = GetClientContextWithOAuth(siteUrl, tenantId, clientId, clientSecret))
{
// Example: Retrieve web title
Web web = context.Web;
context.Load(web, w => w.Title);
context.ExecuteQuery(); // this is throwing 401 unauthorized error
Console.WriteLine("Connected to: " + web.Title);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
private static ClientContext GetClientContextWithOAuth(string siteUrl, string tenantId, string clientId, string clientSecret)
{
// Azure AD OAuth 2.0 endpoint
string authority = $"/*******************";
// Use MSAL to acquire an access token
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
var authResult = app.AcquireTokenForClient(new[] { $"{siteUrl}/.default" }).ExecuteAsync().Result;
if (authResult == null)
{
throw new Exception("Failed to acquire the access token.");
}
// Use the access token to authenticate the ClientContext
var context = new ClientContext(siteUrl);
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.WebRequest.Headers["Authorization"] = "Bearer " + authResult.AccessToken;
};
return context;
}
I tried the sharepoint connection with client id and certificate combination. It's working fine for that where as for the clientid
and secret combination it's throwing 401 error
I am trying to connect the SharePoint site with client id and secret but getting 401 Unauthorized
error while hitting the executequery()
method.
While doing app registrations, both Microsoft Graph and SharePoint API permissions with full site control have been given including trusted the app through appinv.aspx
. Still getting 401 Unauthorized
error.
Since ACS is retiring, do we need to follow any other permissions for share point level site access. The same execute query is working fine for client id, certificate combination. But not working for client id and secret.
static void Main(string[] args)
{
var authManager = new AuthenticationManager("***************************", "C:\\Program Files\\OpenSSL-Win64\\bin\\certificate.pfx", "*******", "********.onmicrosoft");
using (var cc = authManager.GetContext("https://****.sharepoint/sites/****"))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
ListCollection listCollection = cc.Web.Lists;
cc.ExecuteQuery(); // this is working fine
}
;
// Replace with your SharePoint Online details
string siteUrl = "****************************";
string tenantId = "***************************";
string clientId = "********************************";
string clientSecret = "******************************"; // App secret
try
{
using (var context = GetClientContextWithOAuth(siteUrl, tenantId, clientId, clientSecret))
{
// Example: Retrieve web title
Web web = context.Web;
context.Load(web, w => w.Title);
context.ExecuteQuery(); // this is throwing 401 unauthorized error
Console.WriteLine("Connected to: " + web.Title);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
private static ClientContext GetClientContextWithOAuth(string siteUrl, string tenantId, string clientId, string clientSecret)
{
// Azure AD OAuth 2.0 endpoint
string authority = $"https://login.microsoftonline/*******************";
// Use MSAL to acquire an access token
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
var authResult = app.AcquireTokenForClient(new[] { $"{siteUrl}/.default" }).ExecuteAsync().Result;
if (authResult == null)
{
throw new Exception("Failed to acquire the access token.");
}
// Use the access token to authenticate the ClientContext
var context = new ClientContext(siteUrl);
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.WebRequest.Headers["Authorization"] = "Bearer " + authResult.AccessToken;
};
return context;
}
I tried the sharepoint connection with client id and certificate combination. It's working fine for that where as for the clientid
and secret combination it's throwing 401 error
1 Answer
Reset to default 0I’m experienced the same issue. The application access token isn’t working and is returning a 401 error. Once try with the client access token by modifying the code like this.
public async Task<string> GetAccessToken()
{
var tenantId = Configuration.TenantId;
var clientId = Configuration.ClientId;
var authority = $"https://login.microsoftonline/{tenantId}";
var scopes = new string[] { "https://domain.sharepoint/.default" };
var cca = PublicClientApplicationBuilder.Create(clientId)
.WithRedirectUri("http://localhost")
.WithAuthority(new Uri($"https://login.microsoftonline/{tenantId}"))
.Build();
var result = await cca.AcquireTokenInteractive(scopes).ExecuteAsync();
return _authToken = result.AccessToken;
}
return _authToken;
}
reference link
If you found any solution rather than this let me know.