Build Secure Cloud-Hosted Apps for SharePoint 2013


Published on

Apps for SharePoint were introduced in SharePoint 2013 to maximize the level of capability and flexibility that developers can deliver without risking compromise to the farm. In this demo-intensive session, we will delve into apps that leverage resources running outside the SharePoint farm—whether in another on-premises web server or in the cloud. We will use server-side and client-side code to demonstrate how cloud-hosted apps can securely access data stored in SharePoint using the client object model (CSOM/JSOM) and REST APIs, along with the pros and cons associated with each approach. We will discuss the various permissions models associated with apps for SharePoint including types of app permissions, permission request scopes, and how app developers can manage permissions.

Published in: Software, Technology, Business
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • An app package is a ZIP file with a .app extension. If you create a new SharePoint app project named MyFirstApp, the project will generate a app package named MyFirstApp.appas its output. Note that the file format for creating an app package is based on the Open Package Convention (OPC) format. This is the same file format that Microsoft Office begin to use with the release of Office 2007 for creating Word documents (docx) and Excel workbooks (xlsx).So now you understand one of the key points of the SharePoint app model. Custom code never runs inside SharePoint. It runs somewhere else. You have the option of writing both client-side code and server-side code. A SharePoint-hosted app is easier to create, implement and deploy. However, it does not provide the opportunity to add server-side code. A cloud-hosted app will yield more power because you can write as much server-side code as you would like using a managed language such as C# and your code is not limited by all those frustrating limitations and issues created by running code inside the SharePoint environment.
  • You can do a lot more with the app manifest, such as use different authentication schemes (also known as app principals, declare what permissions the app needs to run, and other tasks. Also, do you notice strings like “{StandardTokens}” in the app manifest shown above? These are tokens that are replaced at build/run time. These tokens allow you to reference your app and also pass context (for example, the SharePoint language, where the app is installed, and so on). To learn more about what you can do with the app manifest and tokens, see App for SharePoint manifest file.Within apps, SharePoint 2013 decouples server-side code from the server, enabling you to run server-side code from outside SharePoint, in the cloud. You can host server-side code in autohosted and provider-hosted apps. It is the presence of an inner solution package inside the app package file that tells the SharePoint host whether it needs to create an app web during installation. If the app package does not contains an inner solution package, the SharePoint host installs the app without creating an app web. The inner solution package for a SharePoint app should contain a single Web-scoped feature. The SharePoint host activates this feature automatically on the app web immediately after the app web is created. This features is what makes it possible to add declarative elements such as pages and lists as the app is installed. However, the inner solution package for a SharePoint app cannot contain any type of DLL or any .NET code whatsoever.
  • Hybrid pattern is possible
  • You are responsible for creating the installation, upgrade, and uninstallation logic of the remote components.
  • All Windows Azure and Windows Azure SQL Database components are provisioned for you when the app is installed. Each installation of the app provisions its own Windows Azure Web Site.The Windows Azure Web Sites infrastructure handles load balancing and other important maintenance tasks for you. But this infrastructure is still in preview status, so autohosted apps (which include all apps that depend on Microsoft Access) aren’t being accepted by the Office Store during this preview phase.The infrastructure for autohosted apps will remain in preview status for a period of time after SharePoint 2013 releases. Autohosted apps will not be accepted by the Office Store during this preview phase. We will update with information about autohosted apps as it becomes available.
  • If you look back at the AppManifest.xml file shown earlier, you notice that it did not include a hard-coded path to the app’s start page. Instead, the URL to the start page contains a dynamic token named ~appWebUrl. This dynamic token is replaced by the SharePoint host when the app is installed. This makes sense because the URL that will be used to access the app web is not even known until the SharePoint host creates a new domain for the app during installation. After creating the app web, the SharePoint host can then use it to create the URL to the start page.So why doesn’t the SharePoint host serve up pages from the app web using the same domain as the host site? At first, the reasons why the SharePoint host serves up the pages from an app web in their own isolated domain might not be obvious. There are two primary reasons why the SharePoint app model does this. Both of these reasons are related to security and the management and enforcement of permissions granted to an app.The first reason for isolating an app web in its own private domain has to do with preventing direct JavaScript calls from pages in the app web back to the host site. This security protection of the SharePoint app model builds on the browser’s built-in support for prohibiting cross-site scripting (XSS). Since JavaScript code running on pages from an app web pages originates from a different domain, this code cannot directly call back to the host site. More specifically, calls from JavaScript running on app web pages do not run with the same identity nor the same permissions as JavaScript code behind pages in the host site.
  • Can have multiple user experiences within an app
  • Can have multiple user experiences within an app
  • Can have multiple user experiences within an app
  • <F5> deploy/debugging experience (JavaScript and .NET code)
  • When SharePoint “starts” an app i.e. when a user launches an app, SharePoint packs up some information about that user and passes it along to the app as a POST parameter. This is called the ContextToken and it contains OAuth tokens/information that you need in order to make calls back to SharePoint. Now the trick is that SharePoint passes it to your app when it launches and then it is up to you to do something like cache it so that in subsequent page requests your app has that context and can reuse it.  The basic auth token in it is good for 12 hours & it also contains a refresh token that can be used to get new auth tokens for up to 6 months.When you make the GetSharePointContext(HttpContext) call the class checks the ASP.Net Session state for an existing context. If it doesn’t find one then it creates a new one based on the information passed and then stashes it in Session state for subsequent requests.Then on subsequent requests, when SP hasn’t passed any new tokens, the GetSharePointContext(HttpContext) will return you back the context from Session state. It will also deal with when and if tokens expire.We will discuss authN/authZ in greater detail laterKeep your Office dev tools up to date…there were lots of issues with these in early releases!Classes are the same in provider-hosted or autohosted app projects (same in Web Forms or MVC web application projects)
  • The way I look at it is that I can do just about everything I need to do using the CSOM within a specific site collection. The REST interface on the other hand is mostly brand new in the SharePoint 2013 release. There was a single service in SharePoint 2010 that we could use that enabled read/write to data within a list. The current REST implementation covers a huge area of SharePoint 2013.Rob Windsor Pluralsight course
  • Need to get a SharePoint context because we are outside the SharePoint serverWith a SharePointContext, we can get the necessary ClientContext
  • Same basic steps as CSOM:Create a ClientContext object, passing in the URL of a SharePoint siteCall the Load() function to build the request query for any value properties your application needs to accessExecute the query by calling the ExecuteQuery() function
  • Not a complete code sample
  • Not a complete code sample
  • HTTP verbs match to CRUD operations
  • HTTP verbs match to CRUD operations
  • Pros and cons on both sides, matter of personal preference
  • Azure ACS is used as an authorization server (Automatically set up with O365)
  • User-only – if no permissions are requested by the app (Created by user)User+app – default if permissions are requested by the app (Created by SharePointApp1 on behalf of user)App-only – must be explicitly requested in the manifestApps that do not make OAuth authenticated calls (for example, apps that are only JavaScript running in the app web) cannot use the app-only policy. They can request the permission, but they will not be able to take advantage of it because doing so requires passing an app-only OAuth token. Only apps with web applications running outside of SharePoint can create and pass app-only tokens.In general, a current user is required to be present for a call to be made. In the case of app-only policy, SharePoint creates a SHAREPOINT\APP, similar to the existing SHAREPOINT\SYSTEM user. All app-only requests are made by SHAREPOINT\APP. There is no way to authentication as SHAREPOINT\APP through user-based authentication.When the app-only policy is used, content database authorization checks only take into account the app identity. In particular, when this policy is used, an authorization check succeeds if the current app has sufficient permissions to perform the action in question, regardless of the permissions of the current user, if any.Guidelines for using the app-only policyAll OAuth and server-to-server calls should be user + app policy type calls (not app-only policy type), with the following exceptions. OAuth and server-to-server calls should use the app-only policy if:The app needs to elevate its permissions above the user for a specific call (for example, to approve an expense report under conditions evaluated by the app).The app is not acting on behalf of any user (for example, the call is being made by the app alone, not by a user who is using the app).
  • Today will not be an exhaustive treatment of OAuth.
  • On premises, we have S2S “high trust” apps – certificates/STSFor the apps authenticating with ACS, an access token for SharePoint stays valid for 12 hours once issued, while a refresh token stays valid for six months.
  • A user types a URL in a browser to go to a SharePoint page where a particular app is installed. In this case, the app is a app and the user interface element on the SharePoint page comes from the app.Note If the user is not already logged on, SharePoint 2013 prompts the user to log on.SharePoint processes the page and detects that there is a component from the app on the page. SharePoint must get a context token that it can send to the app. SharePoint asks ACS to create and sign a context token that contains context information (for example, the current user, what web is being rendered on SharePoint, and other context information). It also contains a refresh token.This refresh token inside the context token can be used later by to request an access token from ACS. The server can use the access token to talk back to SharePoint if the app wants to make a web service call to SharePoint later.Note The security token service (STS), ACS in this scenario, is configured and provisioned by SharePoint 2013. The ACS is the tenant in the cloud that does the OAuth authentication. You do not have to configure it. ACS returns the signed context token to SharePoint. The signed context token is signed with a client secret that only ACS and the app share.Note The developer of the app receives the client secret value when the developer registers the app at the Seller Dashboard. SharePoint renders the page, including an IFRAME pointing to the app host server—in this case, When SharePoint renders the page, it also passes the context token to the IFRAME.The IFRAME causes the browser to request a page from the server. The context token is included in the browser request that is sent to the server.The server gets the context token. validates the signature on the context token. The token is signed with a client secret that only and ACS share. can validate that the token is really intended for it and that it is not a random request from some random server. It knows that it is part of a SharePoint request. If the server wants to talk back to SharePoint, there is a refresh token in the context token that can extract, so that it can include that information in the request to ACS for an access token. uses the refresh token that it extracted from the context token, the context token that it got from SharePoint, and its credentials (which are its client Id value and its client secret value) to request an access token from ACS so that it can talk back to SharePoint. Note The developer of the app receives the client Id value when the developer registers the app at the Seller Dashboard. ACS returns an access token to the server. can cache this access token. That way, the server doesn't have to ask ACS for an access token every time that it talks back to SharePoint. (Or, can make an access token request every time and not cache the access token.)By default, access tokens are good for a few hours at a time. Each access token is specific to the user account that is specified in the original request for authorization, and grants access only to the services that are specified in that request. Your app should store the access token securely, because it is required for all access to a user's data. For more information about access tokens, see Authorization and authentication for apps in SharePoint 2013.Note Access tokens are not as long-lived as refresh tokens. By default, refresh tokens are good for about a year. So, the same refresh token can be redeemed for a new access token from ACS for about a year. can use the access token to make a web service call or CSOM request to SharePoint, passing the OAuth access token in the HTTP Authorization header.Note Currently, sample code is provided. The sample code is also included in Visual Studio 2012. In the future, the access token value will be written into the OAuth Authorization field in the HTTP header automatically, via the SharePoint OAuth API calls that the app code makes.SharePoint returns the information that requested to app renders the IFRAME contents as a per-user request in step 1. This completes the OAuth transaction process. The user now sees the SharePoint page fully rendered.
  • For security reasons, Internet Explorer prevents pages that are on different integrity levels (also known as security zones) to share cookies because each integrity level has its own cookie store. The integrity level of a page is determined by its top-most page, and any frame within that page will share the same integrity level. When the remote app page and SharePoint website are in different security zones, the authorization cookies cannot be sent. If there are no authorization cookies, and the IFrame tries to load the proxy page, it will be redirected to the SharePoint sign-in page. The SharePoint sign-in page cannot be contained in an IFrame for security reasons. In these scenarios, the library cannot load the proxy page, and communication with SharePoint is not possible.Best practice: Use the apphost patternTo handle a cross-zone scenario, we recommend that you have an apphost page in SharePoint. The apphost page is a SharePoint page that contains the remote page in an IFrame. Everything inside the IFrame in the apphost page exists in the same security zone as the app web. The cross-domain library in the remote page can receive the authorization cookies and loads the proxy page successfully.
  • You can use appregnew.aspx to register your app if you are going to use the app only in one tenant. For example, if you're creating apps for a single organization and you're going to use an app only within your corporate catalog, you can use appregnew.aspx to get the client Id. You would not be able to use the app in a multitenant scenario. In particular, the client Id cannot be found when used in the context of tenants other than the one where it was created. You also would not be able to publish your app in the Office Store.
  • If you're going to use your app in more than one SharePoint tenant or farm, you should use the Seller Dashboard to register your app. It enables you to use the app in a multitenant scenario. Also, if you intend to publish your app in the Office Store, you have to use the Seller Dashboard to register your app.
  • You do not HAVE to have a local dev VM to do app development!
  • Data can be accessed securely, regardless of whether or not there is a firewall between SharePoint and the external web server
  • Foundation – no significant changes apart from REST supportServer – new APIs added (Microsoft.SharePoint.Client.DocumentManagement, Microsoft.SharePoint.Client.Publishing, Microsoft.SharePoint.Client.Taxonomy, Microsoft.SharePoint.Client.UserProfiles)REST – based on SOAP, much simpler/easier to usePaging may not be supported/working from /_api endpointUpdates using REST require Form Digest (SharePoint pages contain control with form digest; can be acquired through /_vti_bin/sites.asmx)
  • Build Secure Cloud-Hosted Apps for SharePoint 2013

    1. 1. Image from
    2. 2. Image from
    3. 3. Image from
    4. 4. $(document).ready(function () { hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl")); var scriptbase = hostweburl + "/_layouts/15/"; $.getScript(scriptbase + "SP.UI.Controls.js", renderChrome); }); function renderChrome() { var options = { "appIconUrl": "", "appTitle": "CSOM/JSOM/REST demos", }; // 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); }
    5. 5.
    6. 6. using Microsoft.SharePoint.Client;
    7. 7. var SharePointContextProvider using var
    8. 8. "//" "//" var "SPHostUrl" var "SPAppWebUrl" var "/_layouts/15/" "SP.Runtime.js" function "SP.js" function "SP.RequestExecutor.js"
    9. 9. function var new var var new var new var
    10. 10.
    11. 11. 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
    12. 12. Danny's O365 Dev Tenant
    13. 13. CSOM REST Less “chatty” (requests can be batched) More “chatty” (no request batching) 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 vocabularies Can interact with managed metadata taxonomies and workflows No support for interacting with managed metadata taxonomies and workflows Easy to leverage third-party libraries (jQuery) Can be debugged using Fiddler No external assembly references required Table adapted from
    14. 14.
    15. 15. Image from
    16. 16. Requirement/Scenario OAuth Cross-domain I use client-side technologies (HTML + JavaScript). I want to use REST interfaces. There is a firewall between SharePoint and my remote app, and I need to issue the calls through the browser. My app needs to access resources as the logged-on user. My app needs to elevate privileges to other than those of the current logged-on user. My app needs to act on behalf of a user other than the one who is logged on. My app needs to perform operations only while the user is logged on. My app needs to perform operations even when the user is not logged on. Table from
    17. 17. key ClientId value xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx key ClientSecret value xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
    18. 18.
    19. 19.
    20. 20.
    21. 21. us/library/office/fp179934%28v=office.15%29.aspx
    22. 22. developer-tools-for-visual-studio-2013-march-2014-update.aspx
    23. 23. us/library/office/fp179886%28v=office.15%29.aspx
    24. 24.
    25. 25. preference-and-why us/library/office/jj612823%28v=office.15%29.aspx
    26. 26. new-sharepointcontext-helper-in-apps-for-sharepoint-2013.aspx