admin管理员组文章数量:1022726
I want to create a .NET Worker Service (c#) to access files hosted on Sharepoint online.
I have registered an application for this in the Azure portal as follows:
- Register an application (Single tenant)
- API permissions -> Add a permission -> SharePoint -> Application permissions -> Sites.FullControl.All
- Grant admin consent confirmation.
- Certificates & secrets -> Add a client secret
The code looks like this:
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
string siteUrl = "/";
string clientId = "XXX";
string tenantId = "XXX";
string clientSecret = "XXX";
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "/.default" }).ExecuteAsync();
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
};
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title);
}
I get an access token, but access to the SharePoint site is denied (401).
Which step (permissions) may I have fotten?
Thank you very much for your help.
I want to create a .NET Worker Service (c#) to access files hosted on Sharepoint online.
I have registered an application for this in the Azure portal as follows:
- Register an application (Single tenant)
- API permissions -> Add a permission -> SharePoint -> Application permissions -> Sites.FullControl.All
- Grant admin consent confirmation.
- Certificates & secrets -> Add a client secret
The code looks like this:
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
string siteUrl = "https://myname.sharepoint/sites/sharepointwebsite/";
string clientId = "XXX";
string tenantId = "XXX";
string clientSecret = "XXX";
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "https://myname.sharepoint/.default" }).ExecuteAsync();
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
};
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title);
}
I get an access token, but access to the SharePoint site is denied (401).
Which step (permissions) may I have fotten?
Thank you very much for your help.
Share Improve this question edited Nov 26, 2024 at 1:31 Rohit Saigal 9,7242 gold badges24 silver badges34 bronze badges asked Nov 19, 2024 at 14:23 robiwahnrobiwahn 333 bronze badges 2- The error usually occurs if you use client secret while acquiring token to access SharePoint API in app-only scenarios. Switch to client certificate authentication and check if it works. Refer this stackoverflow/questions/78681359/… – Sridevi Commented Nov 19, 2024 at 14:32
- I think @Sridevi is right. Most probably Unauthorized error is because you're using client secret, otherwise you seem to have given permissions and granted consent as per your description. Also make sure to check your scope value after changing to certificate. The other similar question, is in context of a node.js application, so code is a little different. I've provided you a C# version to do the same thing along with some guidance links. – Rohit Saigal Commented Nov 20, 2024 at 3:02
2 Answers
Reset to default 0When you use an Azure AD registered application to authenticate with SharePoint online, you'll need to use a certificate to prove the application’s identity while requesting an access token. In a normal scenario you could use either a secret or a certificate, but AFAIK SharePoint online blocks anything other than certificate. Microsoft documentation for the whole scenario is available here -
- Granting access via Azure AD App-Only
- FAQ > Options other than certificate are blocked by SharePoint online
Step 1 - Associate certificate credential with your registered application
a. If you have a certificate already you don't need to do this part and simply upload the certificate, otherwise you can create a self-signed certificate using the following PowerShell script. (NOTE: self-signed cert may not be good for production scenarios, but can help you verify the concept in dev)
$certname = "MyTestCertificate"
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "C:\WorkFolder\$certname.cer"
$mypwd = ConvertTo-SecureString -String "MyStrongPassword123#" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath "C:\WorkFolder\$certname.pfx" -Password $mypwd
b In the App registrations tab for the client application:
- Select Certificates & secrets > Certificates.
- Click on Upload certificate and select the certificate file to upload.
- Once the certificate is uploaded, the thumbprint, start date, and expiration values are displayed.
Step 2 - Use certificate instead of client secret to acquire token
I've just taken your C# code and modified it to use a certificate.
Important part:
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithCertificate(new X509Certificate2(@"C:\WorkFolder\MyTestCertificate.pfx", "MyStrongPassword123#")).Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "https://myname.sharepoint/.default" }).ExecuteAsync();
Complete code:
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
using System.Security.Cryptography.X509Certificates;
string siteUrl = "https://myname.sharepoint/sites/sharepointwebsite/";
string clientId = "XXX";
string tenantId = "XXX";
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithCertificate(new X509Certificate2(@"C:\WorkFolder\MyTestCertificate.pfx", "MyStrongPassword123#")).Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "https://myname.sharepoint/.default" }).ExecuteAsync();
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
};
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title);
Console.ReadLine();
}
public static void InitializeAuthentication(string clientId, string tenantId, string clientSecret)
{
var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
_graphClient = new GraphServiceClient(credential);
}
I was able to use client id, tenet id, and secret value to connect. No cert needed. NOTE: you MUST use the secret VALUE and NOT the Secret's ID.
I want to create a .NET Worker Service (c#) to access files hosted on Sharepoint online.
I have registered an application for this in the Azure portal as follows:
- Register an application (Single tenant)
- API permissions -> Add a permission -> SharePoint -> Application permissions -> Sites.FullControl.All
- Grant admin consent confirmation.
- Certificates & secrets -> Add a client secret
The code looks like this:
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
string siteUrl = "/";
string clientId = "XXX";
string tenantId = "XXX";
string clientSecret = "XXX";
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "/.default" }).ExecuteAsync();
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
};
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title);
}
I get an access token, but access to the SharePoint site is denied (401).
Which step (permissions) may I have fotten?
Thank you very much for your help.
I want to create a .NET Worker Service (c#) to access files hosted on Sharepoint online.
I have registered an application for this in the Azure portal as follows:
- Register an application (Single tenant)
- API permissions -> Add a permission -> SharePoint -> Application permissions -> Sites.FullControl.All
- Grant admin consent confirmation.
- Certificates & secrets -> Add a client secret
The code looks like this:
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
string siteUrl = "https://myname.sharepoint/sites/sharepointwebsite/";
string clientId = "XXX";
string tenantId = "XXX";
string clientSecret = "XXX";
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "https://myname.sharepoint/.default" }).ExecuteAsync();
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
};
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title);
}
I get an access token, but access to the SharePoint site is denied (401).
Which step (permissions) may I have fotten?
Thank you very much for your help.
Share Improve this question edited Nov 26, 2024 at 1:31 Rohit Saigal 9,7242 gold badges24 silver badges34 bronze badges asked Nov 19, 2024 at 14:23 robiwahnrobiwahn 333 bronze badges 2- The error usually occurs if you use client secret while acquiring token to access SharePoint API in app-only scenarios. Switch to client certificate authentication and check if it works. Refer this stackoverflow/questions/78681359/… – Sridevi Commented Nov 19, 2024 at 14:32
- I think @Sridevi is right. Most probably Unauthorized error is because you're using client secret, otherwise you seem to have given permissions and granted consent as per your description. Also make sure to check your scope value after changing to certificate. The other similar question, is in context of a node.js application, so code is a little different. I've provided you a C# version to do the same thing along with some guidance links. – Rohit Saigal Commented Nov 20, 2024 at 3:02
2 Answers
Reset to default 0When you use an Azure AD registered application to authenticate with SharePoint online, you'll need to use a certificate to prove the application’s identity while requesting an access token. In a normal scenario you could use either a secret or a certificate, but AFAIK SharePoint online blocks anything other than certificate. Microsoft documentation for the whole scenario is available here -
- Granting access via Azure AD App-Only
- FAQ > Options other than certificate are blocked by SharePoint online
Step 1 - Associate certificate credential with your registered application
a. If you have a certificate already you don't need to do this part and simply upload the certificate, otherwise you can create a self-signed certificate using the following PowerShell script. (NOTE: self-signed cert may not be good for production scenarios, but can help you verify the concept in dev)
$certname = "MyTestCertificate"
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "C:\WorkFolder\$certname.cer"
$mypwd = ConvertTo-SecureString -String "MyStrongPassword123#" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath "C:\WorkFolder\$certname.pfx" -Password $mypwd
b In the App registrations tab for the client application:
- Select Certificates & secrets > Certificates.
- Click on Upload certificate and select the certificate file to upload.
- Once the certificate is uploaded, the thumbprint, start date, and expiration values are displayed.
Step 2 - Use certificate instead of client secret to acquire token
I've just taken your C# code and modified it to use a certificate.
Important part:
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithCertificate(new X509Certificate2(@"C:\WorkFolder\MyTestCertificate.pfx", "MyStrongPassword123#")).Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "https://myname.sharepoint/.default" }).ExecuteAsync();
Complete code:
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
using System.Security.Cryptography.X509Certificates;
string siteUrl = "https://myname.sharepoint/sites/sharepointwebsite/";
string clientId = "XXX";
string tenantId = "XXX";
var confidentialClientApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithCertificate(new X509Certificate2(@"C:\WorkFolder\MyTestCertificate.pfx", "MyStrongPassword123#")).Build();
var authResult = await confidentialClientApp.AcquireTokenForClient(new[] { "https://myname.sharepoint/.default" }).ExecuteAsync();
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
};
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title);
Console.ReadLine();
}
public static void InitializeAuthentication(string clientId, string tenantId, string clientSecret)
{
var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
_graphClient = new GraphServiceClient(credential);
}
I was able to use client id, tenet id, and secret value to connect. No cert needed. NOTE: you MUST use the secret VALUE and NOT the Secret's ID.
本文标签:
版权声明:本文标题:c# - Access Sharepoint Online Files from .NET Worker Service via Microsoft GraphOAuth - Unauthorized or Access Denied error (401 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745555100a2155827.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论