build and deploy provider-hosted sharepoint add-ins
TRANSCRIPT
Build and Deploy Provider-hosted SharePoint Add-ins
@dannyjessee#SPSDCOctober 3, 2015
Housekeeping…• Download EventBoard Mobile and remember to fill out session
evaluations…• http://app.spsdc.org
• Phasers set to stun, mobile devices set to silent…• You must be present to win at the wrap-up…
Thanks to our Sponsors!!!
Join us at #SharePint sponsored by Kemp Technologies at World of Beer of Reston in the Towncenter just across the bridge
Why? To network with fellow SharePoint professionalsWhat? SharePint!!!When? 6:15 PMWhere? World of Beer Reston1888 Explorer StreetReston, VA 20190
Thanks toKemp Technologies
We’re hiring!fulcrumco.com/careers
Passed examsSharePoint 201370-331, 70-33270-488, 70-489
Sr. SharePointDeveloperFulcrumWashington, DC metro area
Who Am I?
Photo courtesy Marie Sly | mariesly.com
@dannyjessee
Agenda Intro to provider-hosted Add-ins SharePoint Add-in development tools Accessing SharePoint data remotely Authentication and authorization for SharePoint Add-ins
Deploying provider-hosted Add-ins
Before we go too far… You may have heard of “apps for SharePoint”
Around May 2015, Microsoft began publicizing the name change to “SharePoint Add-ins”
Great “cheat sheet” at http://www.jeremythake.com/2015/06/office-365-app-model-rename-cheat-sheet
Intro to provider-hosted Add-ins
Types of SharePoint Add-ins SharePoint-hosted
Good for very simple solutions (100% client-side code) Can be deployed on-premises or to SharePoint Online in Office 365
Provider-hosted Server-side code deployed to the cloud or a different on-
premises server Hybrid approaches possible
Some components in SharePoint with others in the cloud
Provider-hosted Add-ins Add-in components can be hosted anywhere (cloud or on-premises) Including Windows Azure Web Sites
Authorized using OAuth or the JavaScript cross-domain library
Can use ANY implementation language (ASP.NET, PHP, etc.)
Host, Add-in, and remote webs Each Add-in is deployed to a SharePoint site known as the host web
Add-in web provisioned with Add-in installation https://[Add-in prefix][hash].[Add-in domain]/[relative site URL]/[Add-
in name] Required for SharePoint-hosted Add-ins, optional for provider-hosted
Add-ins (but required if you want to leverage the JavaScript cross-domain library)
Each Add-in installation has its own unique URL Provider-hosted Add-ins also have a remote web Server-side code can run here
Host, Add-in, and remote webs
Image from http://msdn.microsoft.com/en-us/library/fp179925.aspx
Host web
Add-in web
Remote web
Add-in user experiences Immersive full page
Required in every Add-in, whether you need it or not (landing page) Lives in remote web for provider-hosted Add-in (can use SharePoint
chroming) Add-in part
Like a web part; hosted in an IFRAME (can point to content in remote web)
UI custom actions (declarative)
Image from http://msdn.microsoft.com/en-us/library/fp179930.aspx
Styling full page Add-ins Client chrome control can give the basic look and feel of the SharePoint host web$(document).ready(function () { hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl")); $.getScript(hostweburl + "/_layouts/15/SP.UI.Controls.js", renderChrome);});
function renderChrome() { var options = { "appIconUrl": decodeURIComponent(getQueryStringParameter("SPHostLogoUrl")), "appTitle": "CSOM/JSOM/REST demos", "onCssLoaded": "chromeLoaded()" }; // Place the chrome control in the <div> with ID="chrome_ctrl_placeholder" var nav = new SP.UI.Controls.Navigation("chrome_ctrl_placeholder", options); nav.setVisible(true);}
Styling full page Add-ins Before/after client chrome control
SharePoint Add-in development tools
Add-in development tools Office developer tools for Visual Studio http://aka.ms/officedevtoolsforvs2013
Office dev tools for Visual Studio <F5> deploy/debug experience
IIS Express/LocalDB Add components to Add-in project
Provider-hosted Add-ins include ASP.NET project Web Forms and MVC supported (can convert existing projects to Add-
ins)
Office dev tools for Visual Studio
Office dev tools for Visual Studio
Office dev tools for Visual Studio
Office dev tools for Visual Studio
Office dev tools for Visual Studio ASP.NET web application projects include classes to handle Add-in AuthN and AuthZ (using OAuth)
SharePointContext.cs Functions to manage SharePoint context across page requests Can create user and/or Add-in contexts for Add-in and/or host webs
TokenHelper.cs Functions to create and obtain ContextToken and AccessToken
objects On other platforms, you have to do the OAuth implementation and manage tokens yourself
Office dev tools for Visual Studio Convert existing web application project to a SharePoint Add-in project
Demo:Hello World Add-in using Visual Studio with Office Dev Tools
Accessing SharePoint data remotely
Access SharePoint data remotely .NET Managed client object model (CSOM) JavaScript client object model (JSOM) REST endpoints with OData
Can be called via server-side or client-side code Data can be returned in Atom XML or JSON format
.NET Managed CSOM When you create a SharePoint Add-in project, references to the .NET Framework assemblies are automatically added to the project {SharePointRoot}\ISAPI\Microsoft.SharePoint.Client.Runtime.dll {SharePointRoot}\ISAPI\Microsoft.SharePoint.Client.dll
Other CSOM assemblies you may need: …DocumentManagement.dll, …Publishing.dll, …Search.dll, …
Taxonomy.dll, …UserProfiles.dll Add the following statement to your code-behind:
using Microsoft.SharePoint.Client;
.NET Managed CSOMFollow these steps:
1. Create a ClientContext object, passing in the URL of a SharePoint site
2. Call the Load() function to build the request query for any value properties your application needs to access
3. Execute the query by calling the ExecuteQuery() function
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);using (var clientContext = spContext.CreateUserClientContextForSPHost()){ clientContext.Load(clientContext.Web, web => web.Title); clientContext.ExecuteQuery(); Response.Write(clientContext.Web.Title);}
JavaScript client object model Add a reference to the JavaScript client object model (JSOM) using HTML <script> tags Reference the host web URL because the app web may not exist in
every scenario in provider-hosted Add-ins Reference the following libraries, in this order:
1. ASP.NET AJAX library (MicrosoftAjax.js)2. jQuery (optional)3. SP.Runtime.js file4. SP.js file5. SP.RequestExecutor.js file (cross-domain library)
JavaScript client object model<script src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script><script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js" type="text/javascript"></script><script type="text/javascript">var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));var scriptbase = hostweburl + "/_layouts/15/";$.getScript(scriptbase + "SP.Runtime.js", function () { $.getScript(scriptbase + "SP.js", function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execRequests); }); });
JavaScript client object modelfunction execRequests() { var clientContext = new SP.ClientContext(appweburl); var factory = new SP.ProxyWebRequestExecutorFactory(appweburl); clientContext.set_webRequestExecutorFactory(factory); var appWeb = clientContext.get_web(); appWebListColl = appWeb.get_lists(); clientContext.load(appWebListColl); clientContext.executeQueryAsync(onAppWebGetListSuccess, onJSOMError);
var appContextSite = new SP.AppContextSite(clientContext, hostweburl); var hostWeb = appContextSite.get_web(); hostWebListColl = hostWeb.get_lists(); clientContext.load(hostWebListColl); clientContext.executeQueryAsync(onHostWebGetListSuccess, onJSOMError);}
REST endpoints with OData SharePoint 2013 provides a Representational State Transfer (REST) web service that leverages the OData protocol (http://odata.org)
Construct HTTP requests to specially crafted URLs to access and manipulate SharePoint data Responses to these HTTP requests can be returned in Atom or JSON
format Can be used with CSOM, JSOM, or any other stack No external assembly references required!
REST endpoints with OData
URL Returns_api/web/title The title of the current site_api/web/lists/getByTitle('Announcements') The Announcements list_api/web/lists/getByTitle('Announcements')/fields
The columns in the Announcements list
_api/web/lists/getByTitle('Tasks')/items The items in the Tasks list_api/web/siteusers The users in the site_api/web/sitegroups The user groups in the site_api/web/GetFolderByServerRelativeUrl('/Shared Documents')
The root folder of the Shared Documents library
_api/web/GetFolderByServerRelativeUrl('/Plans')/Files('a.txt')/$value
The file a.txt from the Plans library
Table adapted from http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
Example read (GET) request URLs
REST endpoints with OData To get the title of my SharePoint site, construct an HTTP GET request to the following URL:https://djsp.sharepoint.com/_api/web/title
Returned data (if authorized):<?xml version="1.0" encoding="UTF-8"?><d:Title xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:gml="http://www.opengis.net/gml"xmlns:georss="http://www.georss.org/georss" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">Danny's O365 Dev Tenant</d:Title>
CSOM vs. REST Generally a matter of personal preference
CSOM RESTLess “chatty” (requests can be batched) More “chatty” (request batching can only
be done in Office 365, not on-premises)Handles the “plumbing” of calls to SharePoint
Requires you to construct and manage your own HTTPRequest/Response objects
Requires CAML for queries Uses standard OData vocabulariesCan interact with managed metadata taxonomies and workflows
No support for interacting with managed metadata taxonomies and workflowsEasy to leverage third-party libraries (jQuery)Can be debugged using FiddlerNo external assembly references required Table adapted from
http://www.andrewconnell.com/blog/sharepoint-2013-csom-vs.-rest-...-my-preference-and-why
Authentication and authorization forAdd-ins
Authentication and authorization SharePoint Add-ins have distinct identities
Associated with an Add-in principal (just like users have user principals)
OAuth tokens are used to pass Add-in identity
Add-in principal can be granted permissions Add-ins must request permissions to the host web Always has Full Control to the Add-in web
Add-in permissions Add-in manifest must include requests for the scope at which permissions are needed and the permission needed within that scope
Scopes: Permissions:
Add-in authorization policy types User-only
Only the user identity is considered (typical user interactions with SharePoint)
Add-in + User Both the user identity and the Add-in identity are considered “Access denied” if either the user or the Add-in lacks permissions
Add-in-only Only the Add-in identity is considered Allows for elevation above current user’s permissions (or when there
is no current user) Only supported for server-side code in provider-hosted Add-ins Can’t be used with certain APIs (e.g., Project Server, Search)
Add-in permissions Trust must be explicitly granted by the user installing the Add-in (all or nothing)
User installing the Add-in must also have all permissions the Add-in is requesting
OAuth in SharePoint 2013 OAuth 2.0 is an open protocol for authorization http://tools.ietf.org/html/draft-ietf-oauth-v2-22
Enables users to authorize the service provider (in this case, SharePoint 2013) to provide tokens instead of credentials
OAuth is used: To authenticate Add-ins in the Office Store, an Add-in catalog, or a
developer tenant To authorize requests by a SharePoint Add-in to access SharePoint
resources on behalf of a user
OAuth in SharePoint 2013 Windows Azure Access Control Service (ACS) acts as the authorization server for provider-hosted Add-ins
The provider-hosted Add-in uses OAuth to authenticate with SharePoint 2013 SharePoint requests a context token from ACS that it can send to
the provider-hosted Add-in’s server (contains a refresh token) The provider-hosted Add-in’s server uses the refresh and context
tokens (along with its client ID & secret values) to request an access token from ACS
The provider-hosted Add-in’s server then uses the access token to talk back to SharePoint
JavaScript cross-domain library An Add-in that includes a remote web that uses JavaScript for its data access logic likely has to make client-side calls across domains azurewebsites.net (remote web domain) sharepoint.com (host web
domain) By using the cross-domain library (SP.RequestExecutor.js), the pages in your remote web can make client side calls to the SharePoint host and/or Add-in webs on a different domain without the browser blocking them
JavaScript cross-domain library Uses a hidden <iframe> and a client-side proxy page hosted in SharePoint to enable client-side communication using JavaScript Both domains must be in the same IE security zone
Your provider-hosted Add-in must provision an Add-in web in order to use the cross-domain library Can contain just an empty page or list, but the Add-in web must
exist in addition to the remote web
OAuth vs. JS cross-domain libraryRequirement/Scenario OAuth Cross-
domainI use client-side technologies (HTML + JavaScript).I want to use REST interfaces.There is a firewall between SharePoint and my remote Add-in, and I need to issue the calls through the browser.My Add-in needs to access resources as the logged-on user.My Add-in needs to elevate privileges to other than those of the current logged-on user.My Add-in needs to act on behalf of a user other than the one who is logged on.My Add-in needs to perform operations only while the user is logged on.My Add-in needs to perform operations even when the user is not logged on. Table from http://
msdn.microsoft.com/en-us/library/fp179897.aspx
Deploying provider-hosted Add-ins
Deploying Add-ins To use OAuth, you must register an Add-in principal Automatically handled for <F5> localhost deployments Go to /_layouts/15/AppRegNew.aspx for provider-hosted Add-ins
Deploying Add-ins Update <appSettings> values in web.config<add key="ClientId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" /><add key="ClientSecret" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
Set full URL for Start page in AppManifest.xml
Deploying Add-ins Right-click and “Publish…” the Add-in project
Deploying Add-ins
Deploying Add-ins Click Package the app to generate .app file
Deploying Add-ins
Deploying Add-ins Deploy the .app file to your Add-in catalog
Deploying Add-ins Click the link to launch the Add-in Grant permissions the Add-in requests
Demo:Securely accessing SharePoint data from provider-hosted Add-ins,deploying a provider-hosted Add-in, & Add-in authorization policy types
Start building SharePoint Add-ins Office 365 developer site
http://msdn.microsoft.com/en-us/library/fp179924%28v=office.15%29
Free 30-day trial Visual Studio Ultimate/Premium MSDN subscribers get 1-year
subscription (otherwise costs $99/year) Plan E1 or E3 subscribers can provision a developer site from the
Admin Center CloudShare
http://cloudshare.com SharePoint 2013 environments have Visual Studio 2013 Ultimate
preinstalled Azure IaaS (MSDN subscription benefit)
https://manage.windowsazure.com
Conclusion Microsoft has made significant improvements to the developer experience in SharePoint 2013 Almost anything you can do in the server-side object model can now
be done through CSOM, JSOM, REST/OData endpoints Expect continued enhancements to this model in SharePoint 2016 (this is not going away)
Provider-hosted Add-ins allow business logic to be executed on an external server (IIS, Azure, etc.)
Don’t run your server-side code in SharePoint!
Questions?
Thank you!@[email protected]/bloggithub.com/dannyjessee/add-in-model