scot@scothillier.net @scothillier web parts workflows pages libraries app parts sharepoint-hosted...
Post on 28-Mar-2015
214 Views
Preview:
TRANSCRIPT
Build Your Own REST Service with Web API 2Scot HillierMVPScot Hillier Technical Solutions, LLC
SPC404
Scot Hillier
scot@scothillier.net@ScotHillier
From Bricks to Houses
Web Parts
Workflows
Pages
Libraries
SharePoint 2010 SharePoint 2013
App Parts
SharePoint-Hosted Apps
Provider-Hosted Apps
Agenda Building RESTful Services Building OData Services Securing WebAPI Services
Building RESTful Services
REST Constraints Client-Server
Client pulls representations from the server Separation of concerns
Stateless Client provides all necessary context Server returns all necessary state
Cache Responses indicate whether or not they can be cached eTag, Date, Expires headers
Interface Resources are accessible through URIs Resources operations are through HTTP verbs The same representations can be used for all operations Resources are interconnected to allow linking
Layered Resources are unaffected by proxy servers, gateways, etc.
Introducing WebAPI Framework and tooling for building HTTP-
based services RESTful, OData, custom
Part of ASP.NET MVC Uses Controller and Routing paradigm
Tooling, wizards, scaffolding Simplified creation of REST and OData services Simplified use of Entity Framework to wrap database operations
Can be a stand-alone service or part of an app When added to an app, you must make additional manual code
updates
ControllerClient
Model-Client-Controller with Web API
Model
DataHTTP
Controllers Controllers inherit from ApiController
By default methods are mapped to HTTP verbspublic IEnumerable<string> Get() {}
public string Get(int id) {}
public void Post([FromBody]string value){}
public void Put(int id, [FromBody]string value){}
public void Delete(int id){}
public class ValuesController : ApiController
Routing Routes are controlled through maps
Router makes decisions if information is missing
By default methods are mapped to HTTP verbs
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
Responding Content Negotiation is automatic
accept: "application/json" accept: "application/xml"
Return IQueryable to support query syntax
Return HttpResponseMessage for headers and status
public IQueryable<string> Get(){ var d = new List<string>() {"a", "b" }; return d.AsQueryable();}
public HttpResponseMessage Get(int id){ return Request.CreateResponse<string>(HttpStatusCode.OK, data[id - 1]);}
Calling with Managed Code
Calling with JavaScript
DEMO
Creating and Testing a RESTful Service
Building OData Services
Open Data Protocol (OData) Standardized REST API for CRUD
operations Standardized Data Types
Standardized URI format
<Property Name="Id" Type="Edm.Guid" Nullable="false"/><Property Name="Title" Type="Edm.String"/><Property Name="TreeViewEnabled" Type="Edm.Boolean" Nullable="false"/><Property Name="UIVersion" Type="Edm.Int32" Nullable="false"/>
OData Entity Model Service Document
$metadata
Entity Types define entities
Entity Key defines unique property
Associations link entities together
<EntityType Name="Site"><EntityType Name="Web" BaseType="SP.SecurableObject"><EntityType Name="List" BaseType="SP.SecurableObject"><EntityType Name="ListItem" BaseType="SP.SecurableObject" OpenType="true">
<Key><PropertyRef Name="Id"/></Key>
<NavigationProperty Name="RootWeb" …
OData Query Options $select $filter $orderby $top $skip $expand
Controllers Controllers inherit from ODataController
Methods are mapped to HTTP verbs just like ApiController
Content Negotiation is automatic IQueryable generated by default
public class ContactsController : ODataController
Routing Routes are controlled through maps
Router makes decisions if information is missing
By default methods are mapped to HTTP verbs
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();builder.EntitySet<Contact>("Contacts");builder.EntitySet<Company>("Companies");config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
DEMO
Creating and Testing an OData Service
Securing WebAPI Services
General Security Considerations Secure Sockets Layer – always! AuthN, AuthZ
Windows FBA Basic Token OAuth
Same Origin JavaScript API Controllers directly in the app
Cross-Origin JavaScript Cross-Origin Resource Sharing (CORS)
Cross-Origin Resource Sharing Allows JavaScript to make a call across domains Superior to JSONP, which only supports GET Supported in current versions of all major
browsers Browser and resource exchange headers
Origin header from browser Access-Control-Allow-Origin header returned from resource OPTIONS method used for “pre-flight” requests
Enabling in WebAPI2 Install Microsoft ASP.NET WebAPI2 CORS NuGet Package Enable CORS in WebApiConfig Use [EnableCors] attribute in controllers
Cross-Origin Resource Sharing
Pre-flight request
Request Headers
Response Headers
Security Considerations Secure Sockets Layer – always! Always validate calling domain
Allowing all domains can open network to attack
Service not validating domains
Page with malicious script
Script gains access
DEMO
Cross Origin Resource Sharing
On-Premises Apps and Services SSL! Server-to-Server (S2S) High Trust
Windows Authentication required Designing a Service for use solely by your app in same domain Include WebAPI Controllers in same project jQuery ajax calls work from JavaScript in Same Origin
Stand-Alone Services Secure with Windows Auth or Simple Web Token Enable CORS
Cloud Apps and Services SSL! Token-based Security
Simple Web Token OAuth
Enable CORS for stand-alone services
SWT is just HTML form-encoded name-value pairs Audience, the Relying Party. In this case your WebAPI endpoint ExpiresOn, the token expiration Issuer, the token issuing authority Additional custom name-value pairs HMACSHA256, Hash-Based Method Authentication Code of all other
name-value pairs in the token.
Using Simple Web Tokens
Audience=http://myserver.com/apiIssuer=dev.wingtip.comExpiresOn=1255913549role=developerover18=trueHMACSHA256=N4QeKa3c062VBjnVK6fb+rnwURkcwGXh7EoNK34n0uM=
Simple Web Token Flow
MVC5 App(Token IssuingService)
WebAPIService
(Relying Party)
Client
Simple Web Token Flow
MVC5 App(Token IssuingService)
WebAPIService
(Relying Party)
Client
Attempt to accesssecured resource withouta token
Simple Web Token Flow
MVC5 App(Token IssuingService)
WebAPIService
(Relying Party)
Client
Redirected toToken Issuer
Simple Web Token Flow
MVC5 App(Token IssuingService)
WebAPIService
(Relying Party)
Client
Log in andRequest token
Simple Web Token Flow
MVC5 App(Token IssuingService)
WebAPIService
(Relying Party)
Client
Receive access token
Simple Web Token Flow
MVC5 App(Token IssuingService)
WebAPIService
(Relying Party)
Client
Access resourceBy passing token with call
DEMO
Simple Web Token Security
Summary Building RESTful Services Building OData Services Securing WebAPI Services
SPC 413, Complex Problem Solving with HTML5 Tuesday, March 4, 2014, 10:45 AM-12:00 PM Palazzo Ballroom A-H http://curah.microsoft.com/56000/sharepoint-conference-2014-spc413-r
esources
SPC 400, 3rd-Party JS Libraries You Need to Know Tuesday, March 4, 2014, 3:15 PM-4:30 PM Palazzo Ballroom K,L http://
curah.microsoft.com/56018/sharepoint-conference-2014-spc400-resources
SPC 404, Build your own REST service with WebAPI 2 Wednesday, March 5, 2014, 10:45 AM-12:00 PM Palazzo Ballroom A-H http://
curah.microsoft.com/56111/sharepoint-conference-2014-spc400-resources
Sessions and Resources
MySPCSponsored by
connect. reimagine. transform.
Evaluate sessionson MySPC using yourlaptop or mobile device:myspc.sharepointconference.com
© 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
top related