Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - SharePoint App-Only Authentication throwing "The remote server returned an error: (401) Unauthorized."

I am trying to make sharepoint authentication using oAuth or App-Only authentication, but it gives error "The remote server returned an error: (401) Unauthorized."

I am using trial sharepoint tenant.

Here is my code snippets:

Using Client id & Client secret:

string siteUrl = "[Sharepoint-Site-URL]";

//Sharepoint App details
string SPClientId = @"[Client-id]";
string SPClientSecret = @"[Client-secret]";
using (ClientContext context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, SPClientId, SPClientSecret))
 {
     context.Load(context.Web, t => t.Title);
     context.ExecuteQuery();
     Console.WriteLine(context.Web.Title);
 };

Using AccessToken:

 string siteUrl = "[Sharepoint-Site-URL]";
 string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));

 //Get the access token for the URL.  
 string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;

 //Create a client context object based on the retrieved access token
 using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken))
 {
    context.Load(cc.Web, t => t.Title);
    context.ExecuteQuery();
    Console.WriteLine(cc.Web.Title);
 }
enter code here

I referred below articles: https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs https://www.c-sharpcorner.com/article/connect-to-sharepoint-online-site-with-app-only-authentication/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This could be SharePoint app-only permissions is disabled in your tenant.

You could run the command to enabel it: Set-SPOTenant -DisableCustomAppAuthentication $false


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...