Reputation: 2939
I have been really struggling with getting Access Tokens working with our Sharepoint site and still no luck.
The problem is when I access our site using the SharepointOnlineCredentials it works fine, well I can query the sharepoint as follows and this works but I want to use the new token stuff that just doesn't work for me
using (ClientContext context = new ClientContext(sharepointSiteUrl))
{
context.Credentials = GetCredentials();
var web = context.Web;
context.Load(web, w => w.Title);
context.ExecuteQuery();
if (context.Web.IsPropertyAvailable("Title"))
{
Console.WriteLine("Found title");
}
Console.WriteLine("Title: {0}", web.Title);
}
private static SharePointOnlineCredentials GetCredentials()
{
SecureString password = new SecureString();
foreach (char c in "MyPassword".ToCharArray()) password.AppendChar(c);
return new SharePointOnlineCredentials("[email protected]", password);
}
So now for the code that doesn't work
authContext = new AuthenticationContext(authority, new FileCache());
ClientCredential clientCredentials = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = authContext.AcquireToken(resource, clientCredentials);
Console.WriteLine("Token Type: {0} \nExpires: {1} \nToken: {2}", authenticationResult.AccessTokenType, authenticationResult.ExpiresOn, authenticationResult.AccessToken);
using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(sharepointSiteUrl, authenticationResult.AccessToken))
{
var web = context.Web;
context.Load(web);
context.ExecuteQuery();
if (context.Web.IsPropertyAvailable("Title"))
{
Console.WriteLine("Found title");
}
Console.WriteLine("Title: {0}", web.Title);
}
Now when I run this the web.Title throws an error and the context.Web display 'Cannot find the method on the object instance.'
The web.Title in the debugger also states 'The property or field 'Title' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'
I really would love some help with this as it's turned impossible for me. Thanks :)
Do I need to be aware or granting access somewhere else? as its strange that the first one works!
Upvotes: 2
Views: 6856
Reputation: 1503
In the first example you are explicitly requesting the Title
property from the CSOM end-point:
context.Credentials = GetCredentials();
var web = context.Web;
context.Load(web, w => w.Title); // explicitly requesting the Title property
context.ExecuteQuery();
Whereas in the second example there is no context.Load(web, w => w.Title);
Maybe this is the issue?
Upvotes: 1