最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - 401 Unauthorized for ExecuteQuery in sharepoint CSOM - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question edited Feb 16 at 23:30 President James K. Polk 42k28 gold badges109 silver badges145 bronze badges asked Feb 16 at 14:22 DhanushaDhanusha 1 New contributor Dhanusha is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

1 Answer 1

Reset to default 0

I’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.

发布评论

评论列表(0)

  1. 暂无评论