401 Unauthorized when Granting access via Azure AD App-Only

Jack Le 45 Reputation points
2023-01-25T03:58:59.3433333+00:00

I followed this article but I modified the sample code a bit to use GetContextAsync instead of GetAzureADAppOnlyAuthenticatedContext

AuthenticationManager authManager = new AuthenticationManager(clientId, certPath,certPassword,tenantId);
using (ClientContext cc = await authManager.GetContextAsync(_siteUrl))
{
    cc.Load(cc.Web, p => p.Title);
    await cc.ExecuteQueryAsync();
    Console.WriteLine(cc.Web.Title);
}

The error is thrown at await cc.ExecuteQueryAsync(); I have uploaded the self-signed certificate onto Azure portal cert

and granted the permission granted

My app is a Winforms app using .NET framework 4.7 PnP.Framework 1.11

P/s: What do I enter for the tenantId param? At the moment I'm using the Directory (tenant) ID from the Overview page tenant

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,623 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,245 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,668 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 31,071 Reputation points Microsoft Vendor
    2023-01-25T06:35:57.4533333+00:00

    Hi @Jack Le

    In your case, tenantId should be like xxx.onmicrosoft.com

    The code should be like following

    AuthenticationManager authManager = new AuthenticationManager(clientId, certPath,certPassword,"xxx.onmicrosoft.com");
    
    

    If you entered the tenant ID in overview page, the code will return 401 Unauthorized too


    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.