我们在在线共享点时遇到身份验证问题。 我们将Office365身份验证和CSOM API用于c#。 调用“ ExecuteQuery”函数时,我们收到401-异常(未授权)。
static void Main(string[] args)
{
try
{
var service = Office365OAuthTool.Authenticate(new Benutzer(new UnitOfWork()), true);
string value = "https://xyz.sharepoint.com/teams/lab";
var clientContext = TokenHelper.GetClientContextWithAccessToken(value, service.AccessToken);
clientContext.ExecuteQuery();
}
catch (Exception ex)
{
Tracing.Tracer.LogError(ex);
throw;
}
}
已通过Azure配置了应用授权。
但是,可以使用用户名和密码进行身份验证。
其他信息
用户使用Office365凭据登录
然后我们缓存生成的令牌
答案 0 :(得分:0)
不确定是否要使用令牌帮助器,但是使用Azure Api遇到相同的问题。我必须使用证书。
var scopes = new string[] { vURL + "/.default" };
var accessToken = Task.Run(() => GetApplicationAuthenticatedClient(clientId, thumbPrint, scopes, tenantId)).Result;
clientContext = GetClientContextWithAccessToken(siteUrl, accessToken);
Web web = clientContext.Web;
internal static async Task<string> GetApplicationAuthenticatedClient(string clientId, string certThumprint, string[] scopes, string tenantId)
{
X509Certificate2 certificate = GetAppOnlyCertificate(certThumprint);
IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithCertificate(certificate)
.WithTenantId(tenantId)
.Build();
AuthenticationResult authResult = await clientApp.AcquireTokenForClient(scopes).ExecuteAsync();
string accessToken = authResult.AccessToken;
return accessToken;
}
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
private static X509Certificate2 GetAppOnlyCertificate(string thumbPrint)
{
X509Certificate2 appOnlyCertificate = null;
using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);
if (certCollection.Count > 0)
{
appOnlyCertificate = certCollection[0];
}
certStore.Close();
return appOnlyCertificate;
}
}