Applications Server
 

Overview of Oauth in Sharepoint 2013 : Application Authentication (part 2) - Managing Tokens in Your Application

6/27/2014 4:41:51 AM

App and User Context in API Calls

SharePoint provides the ability for apps to make calls to SharePoint with access tokens that are either on behalf of a user or without user context, also known as app-only context. When an access token is used that is on behalf of a user, SharePoint treats the call as if the user is making the call. This means it is subject to the same permissions that user has. Additionally, an app can make an app-only call to SharePoint, which means no user context is passed and only the permissions that the app has been granted apply.

The TokenHelper class provides helper methods for getting each of these types of tokens. To get an access token that includes the calling user’s context, use the following method:

TokenHelper.GetAccessToken

To get an app-only access token, use the following method:

TokenHelper.GetAppOnlyAccessToken

Managing Tokens in Your Application

When an application is launched by a user a context token is passed to it. After this has happened it is up to the application to handle the tokens and potentially store them for future use or pass between app pages. These tasks are left to the application to manage because SharePoint has no knowledge of the inner workings of the application. The developer must decide how she wants to manage these tokens when the application passes them after it is launched. Some basic options are available, including the following:

  • Cache the token for a period of time.
  • Pass the token around as needed but don’t store it.

To assist with caching, the tokens provide a CacheKey and an expiry that can make caching more straightforward for the developer. The CacheKey is a property on the token that is unique to that particular token. It can be used, as the name suggests, as a primary key for that token in a cache of the developer’s choosing, such as ASP.NET application state. Additionally, the expiry time can be used in the application to flush the old tokens from the cache after they have expired.


CACHE THE REFRESH TOKEN
As part of the context token, SharePoint provides another token called a refresh token. This token is typically valid for six months and can be used to request access tokens for a particular user. This capability is very handy if your app needs to make calls into SharePoint as a particular user when the user isn’t using the app; for example, on a timed basis such as a timer job.

The following exercise walks through a simple example of how to use ASP.NET application state to cache the appropriate tokens so that they can be used between page requests.


TRY IT OUT: Caching Tokens (TokenCache.zip)

In this exercise you create an Autohosted application that, when run, receives and then caches the ContextToken using application state.

1. Create a new SharePoint App project in Visual Studio by choosing File ⇒ New ⇒ Project. Select the App for SharePoint 2013 project template.

2. Name your app SharePointTokenCacheApp and click OK.

3. If required, specify the URL of your SharePoint online site for the site to use for debugging.

4. Ensure Autohosted is selected in the hosting type drop-down menu.

5. Click Finish.

6. Locate and open the TokenHelper.cs file.

7. Find the CreateJsonWebSecurityTokenHandler function and make the function public instead of private as follows:
public static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
8. Locate and open the Default.aspx file and add the following code inside the <div> tags:
<asp:Button ID="Button1" runat="server" Text="Process" OnClick="Button1_Click"/>
9. Locate and open the Default.aspx.cs file and replace the contents with the following code:
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.IdentityModel.S2S.Tokens;

namespace SharePointTokenCacheAppWeb.Pages
{
public partial class Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
var contextToken =
TokenHelper.GetContextTokenFromRequest(Page.Request);
var hostWeb = Page.Request["SPHostUrl"];

JsonWebSecurityTokenHandler tokenHandler =
TokenHelper.CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextToken);
JsonWebSecurityToken jsonToken =
securityToken as JsonWebSecurityToken;
SharePointContextToken token =
SharePointContextToken.Create(jsonToken);

Application[token.CacheKey] = contextToken;

Button1.CommandArgument = token.CacheKey;

}
}

protected void Button1_Click(object sender, EventArgs e)
{
var contextToken =
(string)Application[((Button) sender).CommandArgument];
var hostWeb = Page.Request["SPHostUrl"];

using (var clientContext =
TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken,
Request.Url.Authority))
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
Response.Write(clientContext.Web.Title);
clientContext.ToString();
}
}
}
}
10. Press F5 to run and debug the project.

11. If prompted to trust the application, click Trust It.

12. When presented with the list of apps in your site, locate and click your new application.

13. A Web page appears with the Process button on it. Click the button. The page will display the Title of your Website.

How It Works

In this exercise you created a new application that cached the ContextToken passed to it in the ASP.NET application cache. It used the CacheKey property to uniquely key the token in the cache. This allowed subsequent page requests to locate the ContextToken in the cache and use it to make API calls to SharePoint. Without caching the ContextToken in this manner, subsequent page requests or postbacks wouldn’t include the ContextToken in the POST parameters and API calls wouldn’t be possible.
 
Others
 
- Overview of Oauth in Sharepoint 2013 : Application Authentication (part 1) - Using TokenHelper
- Overview of Oauth in Sharepoint 2013 : Creating and Managing Application Identities
- Overview of Oauth in Sharepoint 2013 : Introduction to OAuth
- Sharepoint 2013 : Upgrading to Sharepoint 2013 - Upgrade Considerations (part 3) - Don’t Upgrade Crap
- Sharepoint 2013 : Upgrading to Sharepoint 2013 - Upgrade Considerations (part 2) - What You Can’t Upgrade
- Sharepoint 2013 : Upgrading to Sharepoint 2013 - Upgrade Considerations (part 1) - What You Can Upgrade
- Active Directory 2008 : Managing OUs (part 3) - Delegating Control of OUs
- Active Directory 2008 : Managing OUs (part 2) - Administering Properties of OUs
- Active Directory 2008 : Managing OUs (part 1) - Moving, Deleting, and Renaming OUs
- Microsoft Lync Server 2013 : Installing the Director Role (part 3) - Install Server
- Microsoft Lync Server 2013 : Installing the Director Role (part 2) - Creating a Director Pool - Edit Topology, Publish Topology
- Microsoft Lync Server 2013 : Installing the Director Role (part 1) - Prerequisites
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 10) - Creating public folder mailboxes
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 9) - Creating shared mailboxes
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 8) - Creating arbitration mailboxes, Creating Discovery mailboxes
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 7) - Creating and using archive mailboxes - Creating online archives, Managing archive settings
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 6) - Creating and using archive mailboxes - Creating in-place archives
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 5) - Creating forwarding mailboxes
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 4) - Creating linked mailboxes
- Microsoft Exchange Server 2013 : Creating special-purpose mailboxes (part 3) - Creating equipment mailboxes
 
 
Most View
 
- Business Cases for Lync Server 2013 : Return on Investment (part 2)
- Windows Server 2008 : Creating and Running a PowerShell Script - Running a Script Against Multiple Computers
- Microsoft Project 2010 : Strategic Importance of Project 2010
- Windows 8 : Using the Control Panel Items (part 13) - User Accounts - Adding a Local User Account
- Sharepoint 2013 : Welcome to the Central Administration Web Site (part 1) - Application Management
- Microsoft Project 2010 : Viewing Baselines (part 1) - Tracking Gantt View and the Variance Table
- Sharepoint 2013 : Understanding SharePoint app model architecture (part 2) - Understanding app code isolation
- SQL Server 2012 : Delivering Manageability and Performance (part 8) - OTHER MICROSOFT TOOLS FOR MANAGING SQL SERVER - System Center Operations Manager
- Windows Phone 8 : Groups (part 5) - Pinning a Group to the Start Screen,Deleting a Group
- Microsoft Exchange Server 2013 : Role assignment (part 1) - Using role assignment policy to limit access
 
 
Top 10
 
- Upgrading to Sharepoint 2013 : Upgrading Service Applications
- Upgrading to Sharepoint 2013 : Upgrading Site Collections
- Upgrading to Sharepoint 2013 : Upgrading Content (part 4) - Attaching the Content Database
- Upgrading to Sharepoint 2013 : Upgrading Content (part 3) - Fixing the Issues, Additional Parameters
- Upgrading to Sharepoint 2013 : Upgrading Content (part 2) - Running Test-SPContentDatabase
- Upgrading to Sharepoint 2013 : Upgrading Content - Creating the Web Application, Testing the Content Database
- Windows 8 : Introducing Storage Spaces - Creating storage spaces
- Windows 8 : Working with file systems (part 5) - Working with quotas, Working with quotas for user accounts
- Windows 8 : Working with file systems (part 4) - Understanding Encrypting File System, BitLocker
- Windows 8 : Working with file systems (part 3) - Auditing access to securable objects by using SACLs