Problem of not being able to connect to Sharepoint Online from console application(.net framework)

Buse Kara 26 Reputation points
2024-03-06T15:01:49.1666667+00:00

I want to connect to SharePoint via Console Application with my Azure registration information (client id, client secret, tenant id) and send a request to the /_api/web/siteusers endpoint, but I get a 401 error.

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,680 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,674 questions
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 31,526 Reputation points Microsoft Vendor
    2024-03-07T02:12:21.4533333+00:00

    Hi @Buse Kara,

    You need to use an Azure app. In addition, if you want to use application permissions with the Client Object Model or the REST API, you need to authenticate using client ID and certificate rather than client ID and client secret. The SharePoint APIs will not work with tokens granted application permissions obtained from Azure AD using client ID and client secret.

    The SharePoint APIs will work with tokens granted delegated permissions obtained from Azure AD using client ID and client secret. In addition, Microsoft Graph will work with tokens granted application or delegated permissions obtained from Azure AD using client ID and client secret.

    Here's some sample code that calls to the Client Object Model using a token granted an application permission. This application uses the Microsoft.Identity.Client and Microsoft.SharePointOnline.CSOM Nuget packages.

    using Microsoft.Identity.Client;  
    using Microsoft.SharePoint.Client;  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Security.Cryptography.X509Certificates;  
    using System.Text;  
    using System.Threading.Tasks;  
      
    namespace CsomAzureTest  
    {  
        class Program  
        {  
            private static string tenantName = "4qtfk3";  
      
            static void Main(string[] args)  
            {  
                CallClientObjectModel().Wait();  
            }  
      
            private async static Task<string> GetAccessToken()  
            {  
                var clientId = "e198f2a5-952e-4d35-a641-54b5825d3667";  
      
                var certFileName = @"E:\Certs\MicrosoftIdentityPlatformDemos.pfx";  
                var certPassword = "pass@word1";  
                var certificate = new X509Certificate2(certFileName, certPassword,  
                        X509KeyStorageFlags.MachineKeySet);  
      
                var authority = $"https://login.microsoftonline.com/{tenantName}.onmicrosoft.com/";  
                var azureApp = ConfidentialClientApplicationBuilder.Create(clientId)  
                    .WithAuthority(authority)  
                    .WithCertificate(certificate)  
                    .Build();  
      
                var scopes = new string[] { $"https://{tenantName}.sharepoint.com/.default" };  
                var authResult = await azureApp.AcquireTokenForClient(scopes).ExecuteAsync();  
                return authResult.AccessToken;  
            }  
      
            private async static Task CallClientObjectModel()  
            {  
                var token = await GetAccessToken();  
                var siteUrl = $"https://{tenantName}.sharepoint.com/sites/demo";  
      
                using (var context = new ClientContext(siteUrl))  
                {  
                    context.ExecutingWebRequest += (s, e) =>  
                    {  
                        e.WebRequestExecutor.RequestHeaders["Authorization"] =  
                            "Bearer " + token;  
                    };  
      
                    var web = context.Web;  
                    context.Load(web);  
                    context.ExecuteQuery();  
                    Console.WriteLine(web.Title);  
                }  
            }  
        }  
    }
    
    
    

    In the Azure portal, the Sites.Read.All application permission was granted to the app.

    255716-image.png

    In the Azure portal, the CER file for the certificate was uploaded. Here is the document for reference

    https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azuread


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.