Web Technologies Lecture 11 Implementing RESTful services.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

The OWASP Foundation Web Application Security Host Apps Firewall Host Apps Database Host Web serverApp serverDB server Securing the.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
ASP.NET Best Practices Dawit Wubshet Park University.
1 Configuring Internet- related services (April 22, 2015) © Abdou Illia, Spring 2015.
(4.4) Internet Protocols Layered approach to Internet Software 1.
HTTP By: Becky Fultz, Joe Flager, Katie Huston, Tom Packard, Allison Wilsey.
Chapter 9 Web Applications. Web Applications are public and available to the entire world. Easy access to the application means also easy access for malicious.
Web Servers How do our requests for resources on the Internet get handled? Can they be located anywhere? Global?
Definitions, Definitions, Definitions Lead to Understanding.
Application Layer  We will learn about protocols by examining popular application-level protocols  HTTP  FTP  SMTP / POP3 / IMAP  Focus on client-server.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
Handling Security Threats in Kentico CMS Karol Jarkovsky Sr. Solution Architect Kentico Software
RESTful Web Development With Nodejs and Express. REST Stands for REpresentational State Transfer Has the following constraints: ◦Client-Server ◦Stateless.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Prevent Cross-Site Scripting (XSS) attack
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Chapter 9 Web Applications. Web Applications are public and available to the entire world. Easy access to the application means also easy access for malicious.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
REST.  REST is an acronym standing for Representational State Transfer  A software architecture style for building scalable web services  Typically,
JavaScript, Fourth Edition
Wyatt Pearsall November  HyperText Transfer Protocol.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
Web Application with AJAX CS 526 advanced interned and Web system Presenters Faris Kateb Mohammed AbdulAziz Omar Alzahrani.
Chapter 8 Cookies And Security JavaScript, Third Edition.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Top Five Web Application Vulnerabilities Vebjørn Moen Selmersenteret/NoWires.org Norsk Kryptoseminar Trondheim
CH1. Hardware: CPU: Ex: compute server (executes processor-intensive applications for clients), Other servers, such as file servers, do some computation.
OWASP Top Ten #1 Unvalidated Input. Agenda What is the OWASP Top 10? Where can I find it? What is Unvalidated Input? What environments are effected? How.
Chapter 6 Server-side Programming: Java Servlets
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
REST - Introduction Based on material from InfoQ.com (Stefan Tilkov) And slides from MindTouch.com (Steve Bjorg) 1.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
XHTML & Forms. PHP and the WWW PHP and HTML forms – Forms are the main way users can interact with your PHP scrip Typical usage of the form tag in HTML.
1 Web Servers (Chapter 21 – Pages( ) Outline 21.1 Introduction 21.2 HTTP Request Types 21.3 System Architecture.
ASP.Net, Web Forms and Web Controls 1 Outline Session Tracking Cookies Session Tracking with HttpSessionState.
Appendix E: Overview of HTTP ©SoftMoore ConsultingSlide 1.
1 WWW. 2 World Wide Web Major application protocol used on the Internet Simple interface Two concepts –Point –Click.
IS-907 Java EE World Wide Web - Overview. World Wide Web - History Tim Berners-Lee, CERN, 1990 Enable researchers to share information: Remote Access.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
PHP A very brief introduction PHP1. PHP = PHP: Hypertext Processor A recursive acronym! PHP scripts are executed on the server side Executed by (a plugin.
ICM – API Server & Forms Gary Ratcliffe.
RESTful Web Services What is RESTful?
Web Technologies Lecture 10 Web services. From W3C – A software system designed to support interoperable machine-to-machine interaction over a network.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
Web Technologies Lecture 6 State preservation. Motivation How to keep user data while navigating on a website? – Authenticate only once – Store wish list.
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
COSC 2328 – Web Programming.  PHP is a server scripting language  It’s widely-used and free  It’s an alternative to Microsoft’s ASP and Ruby  PHP.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
1 Chapter 22 World Wide Web (HTTP) Chapter 22 World Wide Web (HTTP) Mi-Jung Choi Dept. of Computer Science and Engineering
JavaScript, Sixth Edition Chapter 11 Updating Web Pages with Ajax.
#SummitNow CORS 6 Nov 2013 / 14 Nov 2013 Jared Ottley / Alfresco Software.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
NCCUCS 軟體工程概論 Lecture 5: Ajax, Mashups April 29, 2014.
#SummitNow What's Coming Arrived in CMIS November, 2013 Gregory Melahn/Alfresco Software
REST API Design. Application API API = Application Programming Interface APIs expose functionality of an application or service that exists independently.
National College of Science & Information Technology.
Servlets.
WWW and HTTP King Fahd University of Petroleum & Minerals
RESTful Sevices Distributed Objects Presented by: Shivank Malik
Better RESTFul API – Best Practices
Data Virtualization Tutorial… CORS and CIS
Node.js Express Web Services
What is REST API ? A REST (Representational State Transfer) Server simply provides access to resources and the REST client accesses and presents the.
Ashish Pandit IT Architect, Middleware & Integration Services
CISC103 Web Development Basics: Web site:
WEB API.
Presentation transcript:

Web Technologies Lecture 11 Implementing RESTful services

REST Services REpresentational State Transfer Stateless Stardard design architecture for web APIs – Allows to publicly expose methods over the Internet to be accessed and manipulated outside the program itself Web services – Get data from an application without having to visit the application itself (e.g., go to a particular website) – Achieved through RESTful URIs Example: GET /mycollection/{id}

Building a RESTful service Use a single URL for the requests – Avoids having multiple URLs increases maintability – Achived through.htaccess rewrite rules Handle cross domain requests to the unique URL – Receive HTTP requests – Extract endpoint from URI – Detect HTTP method (GET, POST, PUT, DELETE) – Assemble additional data provided in the header or URI – Pass information to proper method for processing – Send back HTTP response

Cross Origin Resource Sharing CORS W3C specification Enables cross domain communication – Javascript for instance explicitly prohibits this See AJAX Client and server side – Requires coordination between the two Built on top of XMLHttpRequest Server adds some headers allowing client to access its data NOTE – Not a substitute for sound security practices! – It only allows cross domain access

CORS browser support Image source:

CORS on the client side 1. Create CORS request2. Send the CORS request A valid CORS request always contains an Origin header POST /receiver HTTP/1.1 Origin: The header is added by the browser, and cannot be controlled by the user

CORS on the server side Requires to set up some response headers – Access-Control-Allow-Origin: mandatory – Access-Control-Allow-Methods: list of supported methods. Mandatory – Access-Control-Allow-Credentials: for cookies. Works in conjunction with the withCredentials property on the XMLHttpRequest 2 object – Access-Control-Expose-Headers: allows access to various response headers – Access-Control-Request-Method: the request method. Always present – Access-Control-Request-Headers: list of request headers – Access-Control-Max-Age: allows preflight response to be cahced header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: *"); header("Content-Type: application/json"); PUT and DELET require a preflight request – Extracommunication with the server – Asks permission to make the actual request – Can be cached to avoid making it for every request Source:

The.htaccess file RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule api/v1/(.*)$ api/v1/api.php?request=$1 [QSA,NC,L] 1.Check the existence of mod_rewrite 2.Activate rewrite engine 3.For any request that does not point to an existing file or directory forward it to api.php by using the paramter request QSA: named capture is appended at the end of the URI NC: URIs are not case sensitive L: stop after processing this rule

API class PHP implementation JSON communication format Abstract class defining the basic wrapper for the various endpoints the API will be using Concrete class implementing endpoint functionality Enable secure & cross domain access

API abstract class abstract class API { protected $method = ''; //PUT, GET, POST, DELETE protected $endpoint = ''; //e.g.: /files protected $verb = ''; //e.g.: /files/process protected $args = Array(); //e.g.: /files/process/23 protected $file = Null; // input of the PUT request. Can be JSON text public function __construct($request) { header("Access-Control-Allow-Orgin: *"); header("Access-Control-Allow-Methods: *"); header("Content-Type: application/json"); //extract method, endpoint, verb, args $this->args = explode('/', rtrim($request, '/')); $this->endpoint = array_shift($this->args); if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) { $this->verb = array_shift($this->args); } $this->method = $_SERVER['REQUEST_METHOD']; // search for PUT and DELETE in HTTP_X_HTTP_METHOD if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) { if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') { $this->method = 'DELETE'; } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') { $this->method = 'PUT'; } else { throw new Exception("Unexpected Header"); } switch ($this->method) { case 'DELETE': case 'POST': $this->request = $this->_cleanInputs($_POST); break; case 'GET': $this->request = $this->_cleanInputs($_GET); break; case 'PUT': $this->request = $this->_cleanInputs($_GET); $this->file = file_get_contents("php://input"); break; // read raw post data default: $this->_response('Invalid Method', 405); break; } […] // see next slide }

API abstract class Private methods – _response Sets the response header and body – _cleanInputs Stores the request variables in a key-value list – _requestStatus Returns a message associated with a particular code Used by _response Public method – processApi Determine if the concrete class implements the endpoint method called by the client public function processAPI() { if (method_exists($this, $this->endpoint)) { // call the endpoint method return $this->_response($this->{$this->endpoint}($this->args)); } return $this->_response("No Endpoint: $this->endpoint", 404); }

API concrete class CORS opens up a huge security vulnerability – Must ensure that only certain clients with a unique key can access the API require_once 'API.class.php'; class MyAPI extends API { protected $token; public function __construct($request, $origin) { parent::__construct($request); $User = new User() if (!array_key_exists('apiKey', $this->request)) { throw new Exception('No API Key provided'); } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) { throw new Exception('Invalid API Key'); } else if (!array_key_exists('token', $this->request)) { throw new Exception('No User Token provided'); } $this->token = $this->request['token']); } // Example of an Endpoint. Called by processAPI (see previous slide) protected function returnToken() { if ($this->method == 'GET') { return "Your token is ". $this->token; } else { return "Only accepts GET requests"; }

Using the API // Requests from the same server don't have a HTTP_ORIGIN header if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) { $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME']; } try { $API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']); echo $API->processAPI(); } catch (Exception $e) { echo json_encode(Array('error' => $e->getMessage())); } Note:

What’s next? Node.js Cloud computing