In the previous post, we built a simple contacts list app.
I thought I would spend some more time in exploring the code.
As explained in previous posts, an app has to request permission to access SharePoint resources such as lists, libraries etc., This is handled by OAuth – granting permissions to access all or specified SharePoint resources.
In order to understand the OAuth authentication, please visit the following MSDN article
It is highly recommended to read and understand the flow if you are a developer.
Before diving into this blog post I would like to say that there are many different approaches that a developer can take. What you are reading here is a minimal approach required.
App for SharePoint Web Toolkit (ASWT)
Visual Studio installs a NuGet package on the fly when the ASP.Net web project is created. This NuGet package is called – App for SharePoint Web Toolkit
This package adds the following files and references to the project:
- jQuery Library
- Version 22.214.171.124
ASWT simplifies the job to interact with SharePoint by helping your app get the required OAuth tokens (context token & access token) to access SharePoint resources.
The Code – TokenHelper.cs
Going back to our contacts app, the code starts by getting the context token string:
[Yep, variable name doesn’t make any sense, but it is a String :)]
This retrieves the context token string that is required to get the SharePoint Client Context with which you can now interact with SharePoint
Now that we have the context token string we create the Client Context
using (var clientContext =
TokenHelper.GetClientContextWithContextToken(appWebUrl, ContextToken, Request.Url.Authority))
// query SharePoint
// rest of the code
With this simple approach you are able to easily interact with SharePoint resources from your app in an autohosted app
GetClientContextWithContextToken method does the real magic by getting the following:
1) SharePoint Context Token
2) Access Token
3) Client Context
Below is the code from the file;
public static ClientContext GetClientContextWithContextToken(
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
Refer to the following MSDN article on how to perform common tasks (CRUD) with .NET CSOM:
OAuth, app model, access tokens, context tokens, refresh tokens (yes, there is a refresh token) are all new concepts for SharePoint 2013 development and it is key to understand what they are when building app for SharePoint.
Below are some helpful links to get started: