Using CSOM, Get AAD registered app access token

Madhu J N 1 Reputation point
2022-12-06T06:58:40.723+00:00

Hi Team,

Our product uses CSOM API for SharePoint communication & uses Basic Authentication (we pass Sharepoint user name and password)

As part of new requirement,
We register our product at Azure AD as a Client grant with appropriate API permission sets & Admin Consent granted. Which eventually gives us Client ID and Client Secret

Question is
We need to use client id & client secret for Sharepoint Authentication(internally it authenticates with Azure AD ) using CSOM . Does CSOM supports this way of Authentication & returns access_token , so product can use access token for all SharePoint communication using CSOM like Site Collection, Site , List, List Item CRUD operations.

Thanks,

Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
Microsoft 365 and Office | SharePoint Server | Development
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Tong Zhang_MSFT 9,251 Reputation points
    2022-12-06T08:46:43.613+00:00

    Hi @Madhu J N ,

    According to my research and testing, you can use client_id/client_secret connect to SharePoint Online via CSOM, please refer to the following code:

    string siteUrl = "https://contoso.sharepoint.com/sites/demo";  
    using (var cc = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, "[Your Client ID]", "[Your Client Secret]"))  
    {  
        cc.Load(cc.Web, p => p.Title);  
        cc.ExecuteQuery();  
        Console.WriteLine(cc.Web.Title);  
    };  
    

    More information for reference:
    Granting access using SharePoint App-Only
    Complete basic operations using SharePoint client library code

    Hope it can help you. Thanks for your understanding.


    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.



  2. Madhu J N 1 Reputation point
    2022-12-06T11:26:30.26+00:00

    Hi TongZhangMSFT-7548,

    Thanks for your response.
    I have refered above shared two technical b

    1. Granting access using SharePoint App-Only
    2. https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-client-library-code

    These 2 links, implementation is in place
    Above two links uses Sharepoint generated Client ID and Client Secret & generates SPOIDCRL token

    As i mentioned in my query , our requirement is to certify with Azure AD.
    1.1. Developed a product say ProductAPI - This uses Sharepoint user credentials . ProductAPI uses CSOM for fetching SPOIDCRL token & uses for SharepointOnline Communication
    1.2. ProductAPI registered in Azure AD as a client grant type and given appropriate API permissions & given Admin consent also.
    1.3 As part of #1.2 , Azure AD gives Application (client) ID : <GUID> & Client Secret : <Secret Value>

    Requirement/Expectation is-
    ProductAPI should use #1.3 step Azure AD app registered AppID & secret using CSOM API & get access token which will be used for sharepoint communication using csom.

    We know this feature can be achieved using MS Graph. But we need weather or not CSOM support or not

    Thanks,

    0 comments No comments

  3. Rob Windsor 2,001 Reputation points
    2022-12-06T11:40:49.983+00:00

    These two articles describe how to register an app in Azure AD that requests SharePoint app only permissions and then how to use that app registration with Client Object Model code. Please note, that the Client Object Model does not support the use of client Id and client secret for authentication when using app-only permissions. You must instead use client Id and a certificate. This is covered in the linked articles.

    Accessing SharePoint using an application context, also known as app-only

    Granting access via Azure AD App-Only

    Here's the sample code that's included in the second article. It uses the PnP Framework for authentication.

    using PnP.Framework;  
    using System;  
      
    namespace AzureADCertAuth  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                var authManager = new AuthenticationManager("<application id>", "c:\\temp\\mycert.pfx", "<password>", "contoso.onmicrosoft.com");  
                using (var cc = authManager.GetAzureADAppOnlyAuthenticatedContext("https://contoso.sharepoint.com/sites/demo"))  
                {  
                    cc.Load(cc.Web, p => p.Title);  
                    cc.ExecuteQuery();  
                    Console.WriteLine(cc.Web.Title);  
                };  
            }  
        }  
    }  
    

    Here's some sample code that does the same thing using the Microsoft Authentication Library (MSAL) for authentication. You'll need to add the Microsoft.Identity.Client (MSAL) and Microsoft.SharePointOnline.CSOM Nuget packages to your project to use the code below.

    using Microsoft.Identity.Client;  
    using Microsoft.SharePoint.Client;  
    using System;  
    using System.Security.Cryptography.X509Certificates;  
    using System.Threading.Tasks;  
      
    namespace CsomAzureTest  
    {  
        class Program  
        {  
            private static string tenantName = "contoso";  
      
            static void Main(string[] args)  
            {  
                CallClientObjectModel().Wait();  
            }  
      
            private async static Task<string> GetAccessToken()  
            {  
                var clientId = "<client id>";  
      
                var certFileName = @"C:\temp\mycert.pfx";  
                var certPassword = "<password>";  
                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);  
                }  
            }  
        }  
    }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.