How to Get SharePoint Client Context in SharePoint Apps (Provider Hosted / SharePoint Access ) in CSOM (Client Side Object Model)
First step of the of the app development is to correctly get the access to SharePoint client context. I have struggling with develop a simple model to initialize the SharePoint Client context. Most of the App development include ASP Master pages. So I need to figure out a working model for app development.
First you need to know how SharePoint offer the contextString. contextString Offers when SharePoint is getting redirect from appredirect.aspx url.
that point we need to capture the contextString and generate either AccessToken or RefreshToken and save it for access the SharePoint Client Context in later time. other wise it will result in generating the error The parameter 'token' cannot be a null or empty string (This is nasty error which drove me crazy)
Normally AccessToken is valid for 12 hours and RefreshToken is valid for 6 months.
In my approach I used another key which is called as CacheKey to identify the user uniquely. Therefore I use this value to maintain a cookie based on user the user.
Ref : http://msdn.microsoft.com/en-us/library/office/apps/fp179932
Following shows my approach to do this. If you have master page you need to put the code in the onInit() rather than page load.
protected void Page_Load(object sender, EventArgs e)
{
var key = Session["CashKey"];
// sharepoint url (app hosted url)
var hostWeb = Page.Request["SPHostUrl"];
// Sharepoint url with app Title (app deployed sp url)
Uri SharePointUri = new Uri(hostWeb + "/SharePointApp1/");
// This is first time the app is running
if (key == null)
{
// get the TokenString
var contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
// Get the contexttoken by passing the token string
var contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
//Since some browsers does not support cookie name more than 40 chars
// Im taking first 40 chars
var cookieName = contextToken.CacheKey.Substring(0, 40);
//Add User specific cookie name to the Session
Session.Add("CashKey", cookieName);
// Get the Refresh Token
var refreshToken = contextToken.RefreshToken;
// Add the cookie value (refresh Token)
Response.Cookies.Add(new HttpCookie(cookieName, refreshToken));
}
else
{
// USER already in the applicaiton, means it is not getting redirect from the appRedirect
// So contextstring is null
}
}
this is code for button click
protected void Button1_Click(object sender, EventArgs e)
{
// sharepoint url (app hosted url)
var hostWeb = Page.Request["SPHostUrl"];
// Sharepoint url with app name (app deployed sp url)
Uri SharePointUri = new Uri(hostWeb + "/SharePointApp1/");
// Get the cookie name from the session
var key = Session["CashKey"] as string;
// Get the refresh token from the cookie
var refreshToken = Request.Cookies[key].Value;
//Get the access Token By pasing refreshToken
// 00000003-0000-0ff1-ce00-000000000000 is principla name for SP2013 it is unique
var accessToken = TokenHelper.GetAccessToken(refreshToken,
"00000003-0000-0ff1-ce00-000000000000",
SharePointUri.Authority, TokenHelper.GetRealmFromTargetUrl(SharePointUri));
// Access the Sharepoint Do your work
using (var clientContext = TokenHelper.GetClientContextWithAccessToken("https://rajee.sharepoint.com/SharepointApp1", accessToken.AccessToken))
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
Response.Write(clientContext.Web.Title);
}
}
Note: In the middle of the app if the context broken due to expiation or some other case you need to initialize the app from the AppRedirect therefore you can
var hostWeb = Page.Request["SPHostUrl"];
var val = TokenHelper.GetAppContextTokenRequestUrl(hostWeb, Server.UrlEncode(Request.Url.ToString()));
Comments