我正在开发使用Office 365身份验证的Web应用程序。
我需要访问用户的SharePoint文件。该应用程序是一个多租户应用程序,这意味着我不知道Sharepoint URL,但是我可以使用Microsoft Discover API来发现当前用户的Sharepoint URL。
我想使用该Microsoft.Sharepoint.Client
库访问共享点文件。考虑以下代码:
ClientContext context = new ClientContext("https://discoveredserver.sharepoint.com");
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
我收到未经授权的403,因为客户端对象没有凭据。问题是我无法在运行时设置凭据,因为我没有凭据,我唯一拥有的是Bearer令牌,该令牌允许使用HTTP标头授权连接到Sharepoint API。
有什么方法可以设置Sharepoint客户端中的Bearer令牌来调用Sharepoint Web服务?
下面的例子演示了如何明确指定承载令牌在ClientContext
:
public static ClientContext GetClientContext(Uri webUri)
{
var ctx = new ClientContext(webUri);
ctx.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
{
string realm = TokenHelper.GetRealmFromTargetUrl(webUri); //get the realm
string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, webUri.Authority, realm).AccessToken; //get access token
e.WebRequestExecutor.WebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
};
return ctx;
}
用法
using (var ctx = GetClientContext(webUri))
{
ctx.Load(ctx.Web);
ctx.ExecuteQuery();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句