Question

I have been able to successfully use the ADAL library to obtain an access token to SharePoint Online and execute CSOM queries. When I try to access a SharePoint Online URL directly using a WebRequest, I get a 401 error even though I am setting the authentication header with my bearer token.

When I manually use a web browser to access the URL, everything works. Upon further digging with Fiddler, I see the browser is somehow receiving/using the "rtFa" and "FedAuth" cookies. How can I do the same?

Was it helpful?

Solution

OAuth access tokens work only with SharePoint APIs (_api/*, client.svc). All CSOM requests go through the client.svc, that's why it works fine with adal access tokens. However, it will never work if you try to load a document by url directly with WebRequest object and oauth access token.

You have two options here:

  1. Either attach cookies to your WebRequest and download file. This option has one caveat that you need a real account to obtain cookies, you also should store credentials in your application.
  2. Or use SharePoint search via CSOM to find your document by its documentId (you can extract it from query string, like DocIdRedir.aspx?ID=(document_id)). You should search by the managed property called DocId. Like here for example. However in your case the query will be keywordQuery.QueryText = "DocId:<your document id>";. In the search results you should find the real url of the file. Use CSOM to download the file from a web by its url.

OTHER TIPS

You do not need ADAL library if you are using SharePoint Online C# sdk. Install the nuget package 'AppForSharePointOnlineWebToolkit' and it should install TokenHelper.cs and sharepointcontext.cs. Add app settings for ClientId and ClientSecret . Then use below code

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

            using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken))
            {
                // Your code here
            }

Update: Based on your comments the Pnp Core component from Pnp should solve your problem. Please refer to this link from msdn that shows how to use pnp to get browser pop up. Some of the screenshots are old but the code remains the same. Also please refer to app registration information here.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top