• Share
  • Email
  • Embed
  • Like
  • Private Content
API Workshop Amsterdam presented by API Architect Ronnie Mitra
 

API Workshop Amsterdam presented by API Architect Ronnie Mitra

on

  • 1,082 views

This workshop with Ronnie Mitra, Layer 7's Principal API Architect, will examine the key foundational elements necessary for a solid API implementation strategy. ...

This workshop with Ronnie Mitra, Layer 7's Principal API Architect, will examine the key foundational elements necessary for a solid API implementation strategy.

Building great APIs is about more than just design; it requires detailed, thoughtful execution. Your API strategy needs to meet the business requirements of your organisation but it must also be flexible enough to meet your developer community’s diverse needs.

Statistics

Views

Total Views
1,082
Views on SlideShare
1,080
Embed Views
2

Actions

Likes
2
Downloads
41
Comments
0

1 Embed 2

http://192.168.33.10 2

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    API Workshop Amsterdam presented by API Architect Ronnie Mitra API Workshop Amsterdam presented by API Architect Ronnie Mitra Presentation Transcript

    • Building an API Strategy:Introduction and the Business of APIsRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • API Managementvirtual cloudon-premise
    • API AcademyMike Amundsen Ronnie Mitra
    • www.apiacademy.co
    • Business DriversAPI Styles-- Break --The Developer ExperienceAPI ArchitectureSecuring APIs-- Break --Principles of URI DesignAgenda
    • What areWeb APIs?
    • Connecting things
    • Connecting computer programs
    • APIAll programmers are API designersConnections between modulesLanguage DependantAPIs are constrained by the syntax of thelanguage
    • … over the web
    • Web APIsLanguage IndependentAPIs are constrained by the syntax of the webMost API Design principles can be appliedSome design principles are unique to Web APIs
    • Web ofDocumentsWeb ofAppsWeb ofServicesWeb ofThings
    • The web is ubiquitousAnd universally accessible
    • Publishers retain control
    • Private/Partner or Closed APIs
    • Acme Corp.APIAcme Corp.App
    • Public or Open APIs
    • Acme Corp.APIThird PartyApp
    • Priority:Lower CostPriority:Increased Adoption
    • why build an API?
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • Revenue Source
    • Revenue Sourcehttp://www.flickr.com/photos/inside-south-africa/485356704£0.10 per API Call
    • Revenue Source1000 calls/month5000 calls/month
    • Revenue Source500 calls/month1000 calls/month5000 calls/month
    • Revenue SourceIs your content worth paying for?
    • RevenueSourceInternal Revenue (chargeback)Cost Reduction
    • Revenue SourceStrategy Implications:• Maximize uptime andreliability• Target high revenue consumers• Competitive differentiatorsare a must
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • Consumer Reach
    • Consumer Reach
    • Platforms are not forever!
    • Consumer ReachStrategy Implications:• UX driven interfaces• Specialization may berequired• Difficult to updateapplications
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • MarketingAffiliate ProgramsSometimes you pay the developer.
    • MarketingDraw new visitors in.
    • Marketing
    • MarketingStay above the noise:New channelsInformation-centric marketing
    • MarketingStrategy Implications:• Terms and Services are veryimportant• Identify and reward topperformers• Limit calls and restrictaccess when needed
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • InnovationLight Bulb designed by Jean-Philippe Cabaroc from The Noun ProjectInnovation from within
    • InnovationLight Bulb designed by Jean-Philippe Cabaroc from The Noun ProjectInnovation outside your borders
    • InnovationLight Bulb designed by Jean-Philippe Cabaroc from The Noun ProjectWhen does innovation happen?
    • InnovationLight Bulb designed by Jean-Philippe Cabaroc from The Noun ProjectStrategy Implications:• Design interface for generaluse• Identify success stories• Eliminate misuse
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • IntegrationBusiness driven integrationRegulatory driven integration
    • IntegrationStrategy Implications:• Reduce cost• Reduce cost• Reduce cost
    • Observational Learning:Five Famous Stories of Public APIs
    • 2000 – ebay
    • Started with a paid developer program in 2000Made it free in 2005
    • Consumer ReachMarketing
    • Large developer eco-systemLarge app eco-system
    • 25% of eBay listings come from their API!
    • salesforce2000 – salesforce
    • IntegrationRevenue Source
    • API as a cloud enabler
    • 2004 – Flickr
    • web 2.0 generationthe social evolution
    • Consumer ReachMarketing
    • The rise of self-serviceAnnounced 6 billion photos in August 2011
    • 2006 – Amazon Web Services
    • Started as an online book shop…Became a department store…now?
    • Jeff BezosConnect everythinghttp://www.flickr.com/photos/zippy/2430495092
    • 2004:Hey, why don’t we sell this?
    • Revenue Source
    • Estimated revenue:$1.5B in 2012http://wikibon.org/wiki/v/Cloud_Computing_2013%3A_The_Amazon_Gorilla_Invades_the_Enterprise
    • Twilio or stripe2007 - Twillio
    • Revenue Source
    • The API is the business
    • 100,000 developer milestone in 2012
    • Web API Modern Timeline2000Salesforce APIebay API2002Amazon API2004Flickr API2006Twitter APIFacebook APIGoogle (Maps)API2012Programmableweb.com has7144registeredAPIsSources: apievangelist.comprogrammableweb.cominternetarchive.comSteve Yegge Rantoreilly.com2005ebay makesAPIs free2004First Web 2.0Conference2010Salesforce addsHTTP API2008Programmableweb.com has1000registeredAPIs2005Programmableweb.comlaunched54 APIsregistered.
    • Original APIs are still successfulNew business models have emergedKnow your drivers – design accordinglySummary
    • Building an API Strategy:Introduction and the Business of APIsRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • Building an API Strategy:URI Style Design TipsRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • URI StyleGETPUTPOSTDELETE+ URI
    • URI StyleGET /students/1232
    • URI Style• familiar to web developers• designed for HTTP• URIs are intuitiveAdvantages
    • URI Style• limited to HTTP methods• URI design is not standard• can be ‘chatty’Trade-offs
    • What is ‘good’ API Design?• Easy to learn• Easy to use, even w/o documentation• Hard to misuse• Easy to read and maintain code that uses it• Sufficiently powerful to satisfy requirements• Easy to extend• Appropriate to audienceJoshua Bloch, Principal Software Engineer, Google.
    • Principles of URI Style API Design• URIs should be intuitive and ‘hackable’• The interface should adhere to standards(RFC 2616 and RFC 3986)• The design should be extendable
    • Naming URIs• Names matter!• Establish reserved words and keywords• Names should be meaningful (to theapplication developer)
    • Naming URIs – ExamplesBad:• /Core_Items_DSTSM_1Good:• /charges
    • Defining Resources• Translate interactions into nouns• Build a resource model• Avoid RPC/Tunnel style names• Not everything fits well into theCRUD + Object space
    • Map InteractionsInteraction:“retrieve all my user’s messages”Object:Message
    • Resource ModelMessageTitleAuthorBodyRecipientnnn1n1nn
    • Avoid RPC NamesInteraction:“Retrieve newest messages”RPC-style Name:getNewMessages
    • Not Always EasyInteraction:“Perform a spell-check on thismessage”Object:Message?What method is ‘spell-check’?
    • Not Always EasyInteraction:“Perform a spell-check on thismessage”Object:SpellChecker
    • Types of ResourcesLots of nounsA few operators or controllers
    • Relationshipsmyapi/messagesmyapi/messages/14myapi/messages/titlemyapi.com/ronnie/messages/title
    • RelationshipsDon’t expose relationships unless theyare useful to the developerEach path segment should beactionable
    • HTTP Methods• GET• PUT• POST• DELETE• HEAD• OPTION• TRACE• CONNECT
    • GET• Retrieve a representation• ‘safe’ method according to RFC• no user-requested side effects• won’t impact data• ‘Conditional GET’ is supported withcaching• Don’t abuse for non-read operations
    • PUT• Write a representation• Store the entity (full replacement)• Idempotent• Example:PUT /myapi/messages/14{Message}
    • IdempotenceNo side-effects on identical callsPUT /myapi/messages/14Result: Message ReplacedPUT /myapi/messages/14Result: Message Replaced
    • Full ReplacementPUT /myapi/messages/14{ “title”: “Welcome”}{“id”:”14”“title”:”Wlecome”“author”:”Ronnie”“body”: “Hi Glen, welcome to the team!”}On the Server:{“title”:”Wlecome”}
    • Why not use PUT for partial update?• Breaks HTTP specification• No defined semantic – can produceunexpected results from a devperspective
    • PATCH (Partial Update)• RFC 5789 (HTTP Patch)• Partially update an identifiedresource with the supplied entity• Example:PATCH /myapi/message/14{Partial Message}
    • Patch Media Type• RFC 6902 – JSON Patch• Content-Type: application/json-patch+jsonPATCH /myapi/message/14 HTTP/1.1[{ "op": “replace", "path": "/subject", "value": “new" },{ "op": “add", "path": "/tags", "value": “urgent" }]
    • Challenges with PATCH• Not part of HTTP 1.1 spec• Not widely adopted inimplementations• May not be familiar to developeraudience
    • How do I implement PATCH inan environment that doesn’tsupport it?
    • PATCH WorkaroundsTurn the target data into a URI object:HTTP PUT /myapi/messages/14/title
    • PATCH WorkaroundsTunnel the patch with a custom header:X-HTTP-Method-Override: PATCH
    • PATCH WorkaroundsUse a unique URL:HTTP POST /myapi/patches/messages/14HTTP POST /myapi/messages/14/patchesHTTP POST /myapi/messages/14;patch
    • PATCH WorkaroundsUse PUT and break the specification
    • POST• Write/Process an entity• Accept entity as sub-ordinateresource• Not Idempotent• No identifier specified (factorypattern):POST /myapi/messages
    • Non-IdempotentPOST /myapi/messagesResult: Message #14 CreatedPOST /myapi/messagesResult: Message #15 Created
    • DELETE• Delete identified resource• Example:DELETE /myapi/messages/14• Idempotent
    • Method Tunneling• Older platforms may not support allverbs• Need to resort to embedding theverb in a header or parameter• Example:GET myapi/shops?method=POST• Avoid doing this
    • RepresentationsExpose object properties that arerelevant to the developerEmbed child objects and properties,but need to decide on granularityDesign structures that are extensible –be careful when implementingschema
    • Representations - Granularity{“id” : “14”“title” : “Welcome”“body” : “Hello!”“author” : “38820”}
    • Representations - Granularity{“id” : “14”“title” : “Welcome”“body” : “Hello!”“author” : [ “id” : “38820”,“firstName” : “Ronnie” ]}
    • Representations – GranularityConsiderationsChattiness vs. LatencyFrequency of changeInteraction (what data is needed?)
    • Retrieve a Collection of Data• Example: “Retrieve all storelocations”• GET /shops
    • Retrieve a Filtered Collection of Data• Filter by requesting children• GET /shops/london• GET /shops/amsterdam• Limited to objects and sub-objects• Difficult to retrieve unions/joins of data
    • Retrieve a Filtered Collection of Data• Example: “Retrieve all store locations inLondon”• Use query parameter from URI spec• GET /shops?location=London• GET /shops?location=London,Amsterdam• GET /shops?location=London&sort=distance
    • Complex Queries“retrieve all shops within a radius of 10 kmfrom a specific location that are openwithin specified hours and sell specificphones, devices and account plans”GET/shops?radius=10&location=8882,28832&open_time=38882034&close_time=23882343&phones=iphone,blackberry,samsung&plans=monthly_3GB,monthly_4GB,pay_go_2GB
    • Complex QueriesURI space may be limitedLong queries can become difficult tomanageUse POST on an operator resource:POST /shopsquery{“radius” : “10”, “location” : “388203,838200”,“phones” : [“blackberry”, “iphone”]}
    • Returning Collections• array of results• all properties and child elements?• collection responses can be BIG!
    • Pagination• Just like websites – break data upinto manageable ‘pages’
    • Pagination• data page mechanism/api/resource?page=3• fixed page sizePage 1 Page 2 Page 3 Page 4 Page 5 Page 6• easy to navigate
    • Pagination• offset + count mechanism/api/resource?offset=10&count=20• client app dictates page size10 30• client calculates offset and count forpages
    • Pagination• use links to navigate{“href”:“/api/resource?offset=11&count=20”,“rel”:“next”}• client doesn’t have to calculatelocation• easier to navigate through pages
    • Pagination• use defaults to reduce ‘friction’• reduces learning curve for newdevelopers/api/resource?offset=10&count=20/api/resource/api/resource?offset=10&count=10
    • Field Projection•‘property selection’, ‘zooming’• Collections can be too big for someclient• Allow client to select properties inrepresentations
    • Field Projection - ExampleGET /myapi/messages?fields=title,body{[{“id”: “1”, “title” : “hi!”, “body” :“hello”}…]}
    • Linking• Use links as identifiers{[{“id”: “/myapi/messages/13”},{“id”: “/myapi/messages/14”}]}
    • LinkingAdvantages:• Developer doesn’t need to constructURI• URIs can change!Trade-offs:• Query parameters increasecomplexity
    • Implementing LinkingLots of Standards:• HAL• SIREN• Collection + JSON• ATOM• XML LINKING• HTML
    • Implementing LinkingLots of APIs just do this:{“link_name” : “link”}
    • Implementing Versioning• myapi/v1/path• Try to extend instead of version• Don’t break what is already there• Clients should ignore what theydon’t understand• Introduce breaking changes if youwant to drive developers away.
    • Content Types• XML• JSON• HTML
    • XML• Not the same as SOAP / Tunnel Style• Widely used (AJAX, mobile, server)• W3C Standard, RFC 3023
    • JSON• Usage rising• Popular amongst next-gen developers• JavaScript everywhere• RFC 4627
    • XML vs. JSON?• Not very different• ‘<‘ vs. ‘{‘• Similar performance overhead• Most clients support both (XMLmore widely supported)• What do your developer’s prefer?
    • HTML• Hypermedia content type• Web Form: application/x-www-form-urlencoded• Useful for simple name/value pairinput• Easy for developers to implement
    • Selecting a Representation• Content Negotiation• HTTP Accept Header• URI based• /myapi/messages.xml
    • Status Codes• 1xx: Informational• 2xx: Success• 3xx: Redirection• 4xx: Client Error• 5xx: Server Error
    • Status Codes• You MUST use the correct category• The second part of the code (xx) islargely informational, but stillimportant• Reason phrases can be customized
    • Status CodesClient libraries should handle statuscodes and act in an expected manner
    • Error Handling• You might include an applicationlevel error code• Definitely Include a human readableerror message
    • A Few Interactions
    • Asynchronous RequestClient Resource202 AcceptedFire and Forget
    • Asynchronous RequestClient Resource202 Accepted<link href=“…” rel=“status”/>StatusResource200 OK<status>complete</status><link href=“…” rel=“result”/>
    • Server CallbackClient ResourceRegister200 OK200 OKNotify
    • Server Event (Long Poll)Client ResourceBlock and Wait200 OKHTTP Abuse
    • Optimizations
    • Optimizations• Mobile and device platforms haveunique bandwidth constraints• Transport Level (HTTP)• API Design
    • HTTP Optimizations• Compression• Negotiation (Accept-Encoding)• Example:• Is JSON more efficient than XML?Accept-Encoding: compress, gzip
    • HTTP Optimizations• Pipelining• Multiple requests without waitingfor response• Supported in HTTP 1.1 (persistentconnections)• Idempotent actions only
    • API Design OptimizationsReduce data size (pagination, fieldprojection)Reduce number of calls:• Composition• RPC batch• Caching
    • CompositionURI style APIs can be chattyCombine interactions and expose onthe serverExample:/myapi/composer
    • BatchingURI style APIs can be chattyCombine and invoke calls on the clientCan be complicated for the developer
    • CachingMany forms of cachingHTTP Caching avoids use of networkWidely supported
    • Adaptive Responses• Provide responses that are the bestfit for the calling application•Examples:• Reduced granularity• Different defaults• UI Driven
    • URI Design Summary• Some standards, but lots of choices• Design with developer in mind• Consistency and structure areimportant
    • Building an API Strategy:URI Style Design TipsRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • Building an API Strategy:The Developer ExperienceRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • designing APIs can be difficult
    • http://www.flickr.com/photos/nirufe/3469696707?
    • UsabilityReliabilitySimplicitySecurityEtc…Software Qualities
    • Focus on the developer experience(dx)
    • Interaction DesignBill Moggridge
    • UsabilityHuman-Computer-InteractionUser Experience DesignGoal Oriented Design
    • http://www.flickr.com/photos/58754750@N08/5541472392/
    • A user-centric view of design.
    • Well designed products are easierto use.
    • Good design matters for Web APIstoo.
    • Priority:Lower CostPriority:Increased Adoption
    • PortalAPI
    • PortalAPIDeveloperEnd UserAdministrator
    • PortalAPI
    • This is obvious right?
    • Why is this difficult to do in practice?
    • Reason #1We project our own perspective.
    • Reason #2We project our own biases.
    • Never use SOAP?Why?
    • Consider keyboards…
    • http://www.flickr.com/photos/yvettemn/139890573/
    • http://www.flickr.com/photos/jonathanpberger/7126054997/
    • http://www.flickr.com/photos/novemberborn/286773981/
    • OR
    • It doesn’t matter that you don’t likeSOAP.
    • What matters is what your developerbase thinks!(and what your objective is)
    • Reason #3We make bad assumptions.
    • API publishers are also developers.
    • “I built a mobile app once.”
    • Reason #4We lack the time, money orincentive for good design
    • “Best practices”, patterns andstandards become shortcuts
    • Am I RESTfull enough?
    • So, how can we do better?
    • Developer-centric design requireseffort and diligence.
    • Design with the developer in mind.
    • Ask them.
    • • Interviews• Surveys• Listen (blogs, presentations,tweets)
    • +
    • • Observe• Prototype• Analyze Historical Data
    • Consider all aspects of the DX:RegistrationSecurityTroubleshootingLearningInterface Style
    • A Good DX = A Good System
    • Tunnel StyleURI StyleHypermedia StyleEvent Driven Style
    • RegistrationLazy RegistrationSocial IntegrationPersonalization
    • Development Activity Cycle1. Learn2. Code3. Implement4. Test5. Fix
    • PortalAPILearnCodeTest
    • APILearnTest
    • API explorers and “livedocumentation” can shorten thegap between visibility andfeedback.
    • LearningWADLs and WSDLs are niceBut provide real documentation for humans!Hypermedia =/= zero documentation
    • TLSOAuth 2Open ID Connect
    • SecuritySecurity can hurt UsabilityBut… security can also improve theoverall experience!We need to think about the system as awhole
    • Complexity• Sometimes complexity is necessary –that is ok• Enough features to meetrequirements• Don’t hurt the DX – use structureand modularity
    • Structure and ConsistencyDefine a consistent Message Structure{ “Response” : {“Errors” : {}}}
    • Structure and ConsistencyDefine consistent standards for:• Naming• Collection structure• Content negotiation• Links
    • Structure and ConsistencyEnforcing standards requiresorganizational disciplineEspecially difficult in largeorganizations!
    • ModularityPartition APIs into modules orproductsFrom a DEVELOPER perspective!
    • “Frictionless” integrationHigh rates of adoptionLow cost integrationWe want:
    • Behaviour DesignBJ Fogg
    • Visitor Invested Developer
    • JoyVisitorInvested DeveloperJoyJoy
    • A Sample DX Based Design Process
    • 1. Define the problem space2. Design interactions3. Map the interaction to an APIstyle4. Prototype and get feedback5. Iterate
    • The Problem SpaceWhy are we doing this?Who are we building it for?
    • InnovationConsumer ReachRevenue SourceMarketingIntegrationLight Bulb designed by Jean-Philippe Cabaroc from The Noun Project
    • Consider:PlatformsOrganizationsLanguagesWho is this for?
    • The Problem SpaceWhat are our:Assumptions?Constraints?Shared terms and jargon?
    • Data GatheringHow do we learn about our targetaudience?
    • Interaction ModelDefine requirements:What interactions will benefit thedeveloper?What information is required tosupport the interaction?
    • Interaction ModelAs a ___ I want to …
    • Map Interactions to an API DesignWhich style?Which formats?How do we translate interactions?
    • PrototypeDon’t bind to real data or backendUse something lightweight and easyto changeDo this early
    • Practical PrototypingWrite simple code or script in a languagethat is easy for you to implement.var express = require(express),app = express();var port = 8080;app.listen(port);app.get("/tasks", function(req, res) {res.status(200).send(‘<response><tasks><task><name>Pick up Kai</name><priority>1</priority></tasks></response>’);}
    • Practical PrototypingConfigure an interface in a web or APIplatformGET /tasks
    • Practical PrototypingApply minimal securityTry writing throwaway client codeAsk target developers to write code anduse the APIMake quick changes and try it again
    • Focus on the interactions that takeplace, rather than the interfaceswe expose
    • DX > Software Qualities
    • Usability Summary• Focus on the developer• Start by thinking in terms of interactions• Effective for public and private APIs
    • Great API design can thrive in adeveloper-centric environment
    • Building an API Strategy:The Developer ExperienceRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • Building an API Strategy:Architecture FoundationsRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • Architecture
    • http://www.flickr.com/photos/naomi_pincher/3306312873/Layered Pattern
    • Representation Layer
    • Component != Connector
    • ComponentDatabaseFile SystemMessage QueueTransaction ManagerSource Code
    • Components Are Private
    • ConnectorWeb ServerBrowser AgentProxy ServerShared Cache
    • Connectors Are Public
    • Client ServerConnectorsComponentsThe Web
    • Representation Layer Representation happens in the Connector HTTP supports content negotiation- Accept- Content-Type Differing clients (user-agents) === differing representations- Desktop- Browser- Tablet- Smartphone Be prepared to support multiple representations
    • • Data and Interface Transformation• Focus on the interface (usability)RepresentationSOAPLegacy
    • Security Layer
    • Security implementations are difficult:• Mistakes are costly• Hard to understand specifications• Performance can suffer
    • Don’t implement API security in the implementationEnforce security at the edgeWhere?
    • Caching Layer
    • Caching Layer
    • Caching Layer Caching happens EVERYWHERE HTTP supports Expiration Model and Validation Model Caching Expiration Model- Expires- Cache-Control: max-age Validation Model- Last-Modified- Etag, If-Match Be prepared to support caching for both client and server Squid, Varnish, Nginx, MemCacheD, NSURLConnection etc.
    • Orchestration Layer
    • • Chaining multiple calls• Aggregating and enriching data• ‘mashup’ external data with internal dataOrchestration:
    • Gateway Pattern Abstraction of multiple interfaces In Software Engineering: Façade Pattern Benefits:- Deliver a consistent experience- Centralize API functionalityhttp://martinfowler.com/eaaCatalog/gateway.html
    • API GatewayGatewayAPIAPI
    • Restrict AccessImprove PerformanceFocus on Usability
    • The gateway doesn’t solve all our problems
    • API portalsPortal
    • API ManagementPortalGatewayAPIAPI
    • Nuts and Bolts of API Management Developer Registration Access Control API Explorer API Documentation Social Engagement Tracking and Reporting
    • We also apply this philosophy behind the firewall.
    • Architecture Summary• Use a layered architecture• Deploy a gateway for runtime• Deploy a portal for developers
    • Building an API Strategy:Architecture FoundationsRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • Building an API Strategy:The Security ChallengeRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy
    • The API security challenge:BalancingControl and Accessibility
    • IdentityAuthenticationAuthorizationAvailabilityIntegrityPrivacy
    • Attack Surfaces and Identities
    • PortalAPIDeveloperEnd UserAdministrator
    • PortalAPIDeveloperEnd UserAdministrator
    • APIEnd User
    • Injection AttacksUtilizing input parameters to inject data that compromisesthe security of the targeted system. Examples:- SQL Injection- Command Injection- Code Injection- Argument Injection
    • API Attack Example:SQL Injection Attacks: APIsGET http://host.com/aresource?token=%E2%80%98or%20%E2%80%981%3D1GET http://host.com/aresource?token=‘ or ‘1=1select * from tokens where token = ‘’ or ‘1=1’;
    • APIs May Be A Direct Conduit292HTTPServerAppServerDatabaseAppObjectsOften:• Self-documenting• Closely mapped to object space
    • Denial Of Service AttacksAn attack which has the objective of making a serviceunavailable to all usersExamples:- XML/JSON parser attacks- Jumbo messages- Server overload
    • Overflow AttackIntentionally sending too much data in order to exploit atarget systems by exceeding expected boundaries.Examples: Buffer Overflow Cash Overflow
    • Cross Site Scripting (XSS) AttackEmbedding code within a server that will betransmitted to users.
    • XSS API Example296AttackerWeb App Server(browser+APIs)Victim: WebBrowserClient<SCRIPT …>1. API injectsscript in3. Browser loadscontent withembedded script2. Server fails toperform FIEO: FilterInput, Escape OutputAPI
    • Interception of communication between two systems.Man in the Middle Attack
    • OWASP Top Ten (2010 Edition)Source: http://www.owasp.org/index.php/Top_10
    •  Impersonating a registered application in order to accessan API resource. Examples:- Guessing application ID by brute force- Retrieving application ID by sniffing traffic- Cracking application to retrieve application IDApp Spoofing
    • how can I protect identity on a mobile device?
    • what happens if my mobile app is impersonated?
    • APIEnd User
    • Revenue Source
    • What the Fudge*! Ididn’t make 10000calls yesterday!!!!!!I’m not paying that.*This is what WTF actually stands for.
    • I didn’t buy 1000mobile phones inRussia!I’m not paying that!
    • Forrester:we are moving towards a ‘zero-trust’ model
    • New platforms, new languages:• Ruby on Rails• Node.js• Scala• Nginx• Squid/Varnish/Traffic Manager
    • TLSOAuth 2Open ID Connect
    • OAuth provides aDelegated Authorization Framework
    • An imperfect analogy….
    • http://www.flickr.com/photos/drewleavy/5587005480
    • http://www.flickr.com/photos/24oranges/5791460046/
    • http://www.flickr.com/photos/grumbler/571106054/http://www.flickr.com/photos/roboppy/238406811/Your MoneyThis Shop Needs Your MoneyYou need to grant accessto your money
    • http://www.flickr.com/photos/drewleavy/5587005480I won’t tell.I promise!
    • www.flickr.com/photos/auntiep/255249516
    • Granting access to someone to acton your behalf.
    • Your resourcesThis app needs to act on your behalfYou need to grant accessto your resources
    • Your google+ dataThis app needs to access yourGoogle+ dataYou need to grant accessto your resources
    • Hi Google.I’d like to have access to a user’sdata.
    • Hang on, let meask…
    • He said yes. Here is youraccess code.
    • “Client” == application“Resource owner” == end-userThe first step to understanding OAuth 2:
    • OAuth 2 Grant Types- Authorization Code- Implicit- Resource Owner Password Credentials- Client Credentials
    • Authorization Code Grant326Client ApplicationResource OwnerUsingApplicationResource ServerI Wish I could accessmy resources throughthis application…
    • Authorization Code Grant327Client ApplicationResource OwnerUsingApplicationResource Server…but I don’t trust thisapp enough to give itmy credentials.
    • Authorization Code GrantInitiation328Client ApplicationResource Owner Authorization ServerResource ServerUser AgentIssue GETrequest viaUser-Agent
    • Authorization Code GrantInitiation329Client ApplicationResource Owner Authorization ServerResource ServerUser AgentIssue GETrequest viaUser-Agentresponse_typeclient_idredirect_uriscopestate
    • OAuth 2 Authorization Request response_type – indicates grant type client_id –application identifier redirect_uri (optional) – address which the UA can use to respond to client scope (optional) – space delimitted string: what the client wants to do state (optional)– opaque string used to defeat CSRF attacks Sample Authorization GET URL:https://azserver/oauth2/authorize?response_type=code&client_id=my_id&state=state&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback
    • Authorization Code GrantResource Owner Authentication331Client ApplicationResource Owner Authorization ServerResource ServerUser AgentSendUserAuthenticationForm?Authenticate
    • Authorization Code GrantAuthorization332Client ApplicationResource Owner Authorization ServerResource ServerUser AgentDeliverGrantScreen???ApproveGrantRequest
    • Authorization Code GrantReceipt of Authorization Code333Client ApplicationResource Owner Authorization ServerResource ServerUser AgentRedirectUser-AgentClientApplication! RedirectedToClientApplicationcodestate302
    • Authorization Code GrantAccess Token Request334Client ApplicationResource Owner Authorization ServerResource ServerRequestAccessTokenReturnAccessTokenand OptionalRefresh Tokengrant_typecoderedirect_uriclient_id200AZ CodeAZ Code
    • Authorization Code GrantAccess Protected Resource335Client ApplicationResource Owner Authorization ServerResource ServerRequestResourceUsingApplicationReturnResource200
    • Authorization Code Grant - Summary Most Complex of OAuth 2 Grant Types Provides full OAuth 2 capability
    • 2 vs. 3 Legged Spectrum337ThreeleggedTwolegged
    • OAuth 2 ChallengesIt is a framework
    • OAuth 2 Challenges New attack surfaces Flexible, but complex for API publishers to implement Utilizes redirection URIs (should be validated with strong rules) Poor implementations will be exposed (see Facebook) Not a solution to user authentication
    • OpenID Connect Identity Access and Authentication (when combined with Open ID) Built on top of OAuth 2 Not tied to any single vendor or identity provider
    • Open ID, Open ID Connect and OAuth 2 OAuth 2 allows an end-user to grant an application access to protected resources However:- The authorization server must still authenticate the end-user- The client application is unable to determine information about the end-userClient ApplicationResource Owner Authorization ServerUser AgentSendUserAuthenticationForm?Authenticate
    •  OpenID Authentication can help the server authenticate the end-user OpenID Connect provides a mechanism for the application to learn about the end-userOpen ID, Open ID Connect and OAuth 2Client ApplicationResource Owner Authorization ServerUser AgentSendOpenIDAuthenticationFormAuthenticateRetrieve UserInformationOpenIDResourceServer
    • Portal
    • Who is using the API?How are they (mis)using it?
    • What would happen if the portal was exploited?
    • PortalAPIDeveloperEnd UserAPI
    • PortalAPIAdministrator
    • Where are the components deployed?Who owns the identity store?
    • PortalAPI
    • Summary:Challenge: Balancing Usability and SecurityOld Threats Still ExistNew Styles and Access Models create new surfaces
    • Building an API Strategy:The Security ChallengeRonnie MitraPrincipal API Architect - EuropeLayer 7 API Academy