Designing Web Applications in PHP Martin Kruli by
Designing Web Applications in PHP Martin Kruliš by Martin Kruliš (v 1. 2) 20. 3. 2018 1
Web Application Architectures � Traditional Web Applications HTTP request /var/www/myweb/ ` mod_php Internet Client Web Server index. php HTTP response with contents generated by a PHP script Database by Martin Kruliš (v 1. 2) 20. 3. 2018 2
Web Application Architectures � Single Page Applications (SPA) Internet Client Browser downloads static content (HTML, JS, …) Web Server AJAX, Web. Sockets, … HTML document and scripts ajax. php by Martin Kruliš (v 1. 2) 20. 3. 2018 3
Web Application Architectures � Other Shades of Grey ◦ Traditional Applications with AJAX �Isolated operations are handled directly in the browser �Form validation and autocomplete �Paginated view for long repetitive content (tables) �Simple single-click operations (e. g. , deleting a record) ◦ Multiple Connected SPAs �Integrating multiple SPA into one larger application which share the user session �Typically used when a larger project is created as a composition of independent smaller projects by Martin Kruliš (v 1. 2) 20. 3. 2018 4
Traditional Web Applications � Expressing UI in the Browser ◦ Browser was originally designed as a viewer for static contents (HTML pages) ◦ Hyperlinks as controls �Leading to the same page with different query params �Changing application state of requires HTTP request �Only the view state can be changed (HTTP GET request) ◦ Forms �Smarter forms of hyperlinks (e. g. , filter form) �Can use POST request to insert/update/delete data at server side �Single-button forms (like hyperlinks for POST actions) by Martin Kruliš (v 1. 2) 20. 3. 2018 5
HTTP Wrapper (Revision) � Request ◦ Automatically parsed into superglobal arrays �$_GET – parameters from request URL �$_POST – parameters posted in HTTP body (form data) �$_FILES – records about uploaded files �$_SERVER – server settings and request headers �$_ENV – environment variables � Response ◦ Script output is included in body of the response ◦ Headers may be modified by a function �header('header-line'); by Martin Kruliš (v 1. 2) 20. 3. 2018 6
Dealing with Statelessness � HTTP Is Stateless ◦ Applications require state (logged in user, contents of a shopping cart, currently selected page, …) Temporary Server Side Client Side Sessions Passing on parameters in URL JS, web storage Persistent Database, Files, … Cookies by Martin Kruliš (v 1. 2) 20. 3. 2018 7
Dealing with Statelessness � Passing on URL Parameters ◦ URL query parameters are not automatically kept ◦ Must be manually added to all generated URLs �Hyperlinks, form action fields, redirects, … �Such a task is quite tedious and error prone ◦ Use a framework/function for generating URLs �Automatically adds (sanitized) parameters from $_GET �Or more likely from an object which manages the params. �Other smart features can be added �Removing defaults, merging values, … Example 1 by Martin Kruliš (v 1. 2) 20. 3. 2018 8
Dealing with Statelessness � Cookies (Revision) ◦ A way to deal with stateless nature of the HTTP ◦ Key-value pairs (of strings) stored in the web browser �Set by special HTTP response header �Automatically re-sent in headers with every request �Each page (domain) has it own set of cookies ◦ Cookies in PHP �Cookies sent by browser are loaded to $_COOKIE[] �Cookies are set/modified/removed by setcookie() �The function modifies HTTP response headers by Martin Kruliš (v 1. 2) 20. 3. 2018 9
Dealing with Statelessness � Session ◦ Identification of a client over multiple HTTP req. ◦ Essential when user authentication is required ◦ Session ID must be kept at both client and server �Client – in URL query parameters or in cookies �Server – special storage with additional associated data � Session Hijacking ◦ One of the greatest security concerns of web apps. ◦ HTTPS must be used when session is maintained ◦ ID must be sufficiently long (hundreds of bits) and regenerated periodically by Martin Kruliš (v 1. 2) 20. 3. 2018 10
PHP Session API � Opening Session ◦ Simple call to session_start() method ◦ Checks $_COOKIE and $_GET arrays for PHPSESSID variable which should have the ID ◦ If the variable is missing, new session is started �And a cookie with the new ID is set (if php. ini says so) � Accessing Session Data ◦ In the $_SESSION global array ◦ It can be read and written (incl. unset() on items) by Martin Kruliš (v 1. 2) 20. 3. 2018 11
PHP Session API � Removing the Session ◦ session_unset() – clears the session (keeps the ID) ◦ session_destroy() – invalidates the session ID � Others ◦ session_name() – gets/sets name of the variable for the session ID (PHPSESSID by default) ◦ session_id() – get/sets current session ID ◦ session_regenerate_id() – generate a new ID ◦ session_cache_expire(time) – sets time (in minutes) after which the session expires if not used Example 2 by Martin Kruliš (v 1. 2) 20. 3. 2018 12
PHP Session API � Session Internals ◦ Sessions are saved to files by default �Can lead to race conditions in some special cases �Optionally SQLite or memcache can be used (configured by session. save_handler in php. ini) ◦ Session. Handler. Interface �Specifies methods for session saving, loading, … �open(), close(), read(), write(), destroy(), gc(), create_sid() �Implemented by Session. Handler class �Performs the saving according to php. ini �session_set_save_handler($handler. Obj) Example 3 by Martin Kruliš (v 1. 2) 20. 3. 2018 13
Dealing with Statelessness � Where to put which parameters? ◦ URL query ($_GET) �Short term parameters (“changed” by hyperlinks) �Parameters affecting visualization (paging, filters, …) �Parameters that can be (effectively) bookmarked ◦ Session ($_SESSION), or possibly database �Parameters changed only on POST requests �User-related parameters (identity, shopping cart, …) �Parameters that should not be “visible” in URL ◦ Cookies ($_COOKIE) �Long term parameters (lasting between sessions) �User identification, security tokens by Martin Kruliš (v 1. 2) 20. 3. 2018 14
Forms � Study Case – Editing Form ◦ Edit personal data of existing user <form action="? " method="POST"> Full Name: <input name="fullname" type="text" value="Martin Kruliš"> Date of Birth: <input name="born" type="date" value="14. 4. 1984"> Married: <input name="married" type="checkbox" checked> Children: <input name="children" type="number" value="1"> <input type="submit" value="Save"> </form> Various data types (string, date, bool, and integer respectively) by Martin Kruliš (v 1. 2) 20. 3. 2018 15
Forms � Study Case – Editing Form ◦ Major concerns �Appropriate mapping between HTML form and PHP script processing its POST request �Item names, types, … �Data are transferred as strings (no matter orig. type) �Two level sanitization (client side, server side) �What to do when the server side validation fails �Data has to be loaded from the database (existing user) �Mapping DB object data to form elements �Some data may not be editable by the form �Which data to show when the server side validation failed and the form is being re-shown with errors by Martin Kruliš (v 1. 2) 20. 3. 2018 16
Redirect Revision � Redirect (303 See Other) after POST Request add/change something Redirect (new URL) Client (Browser) Refresh Redirects to a new URL (without updating history) GET (new URL) Web Server read-only HTML Page by Martin Kruliš (v 1. 2) 20. 3. 2018 17
Forms � Study Case – Editing Form ◦ Form Component �Each form is represented by one object �Responsible for rendering and HTTP data processing �And handling the serialization or data conversions ◦ Sticky Forms �Form remembers user inputs even if they are incorrect �I. e. , even if a result was not saved to the database and the form needs to allow the user fix the input mistakes �Data are stored in a session �Additional identifier is required that is passed to the URL query parameters (in case multiple windows are opened) Example 4 by Martin Kruliš (v 1. 2) 20. 3. 2018 18
Flash Messages � Study Case – Flash Messages ◦ Notifications that should appear exactly once �E. g. , “the data were saved”, “the e-mail was sent”, … �Non-persistent error messages ◦ Where to put the text (or ID) of such message, if… �The message should not get lost nor it should be displayed long after the operation is finished �The user may click refresh button �The user may use back/forward buttons �The user may copy/bookmark the URL �The HTTP request may be interrupted and refreshed by Martin Kruliš (v 1. 2) 20. 3. 2018 19
Web Application Design � Front Controller ◦ Software design pattern that provides centralized entry point for all request (commands) ◦ All URLs point to the same script �Actual action is determined from URL query parameters Initializing the libraries, setting up components HTTP Front Controller (index. php) Action … Controller/Presenter … dispatching Routing and Action Controller/Presenter by Martin Kruliš (v 1. 2) 20. 3. 2018 20
Web Application Design � Model-View-Controller ◦ Design pattern that clearly divides responsibilities Controller Encapsulates data loading and data manipulation (e. g. , in a database) s te Pr a ul ip an M ep ar es Handles business logic. Action of the controller is invoked by dispatcher View Loads data from Model Responsible formatting (presenting) data in HTML (JSON, XML, …) by Martin Kruliš (v 1. 2) 20. 3. 2018 21
Web Application Design � Model-View-Presenter ◦ A derivation of MVC pattern �Presenter have similar role as controller ◦ Presenter strictly separates model and view �View should no longer access model directly �Data from model are passed to view by presenter View Send events Prepares Presenter Updates Model Send data by Martin Kruliš (v 1. 2) 20. 3. 2018 22
Views � Templates ◦ Libraries that help with formatting the data (HTML) �Simplifying syntax (abstracting from low level PHP) �Providing additional functions formatting �Date, time, currency, … �Handling data sanitization (preventing script injection) �Handling language translations ◦ The controller/presenter prepares the data for the view and the view fills them into the template ◦ Many approaches to templating exist �Simple frameworks rely on PHP-HTML interleaving, complex ones use their own syntax and preprocessing by Martin Kruliš (v 1. 2) 20. 3. 2018 23
Views � Latte Templates Example The same text will appear in the title of the page <h 1 n: block=title>Latte Example</h 1> If and foreach are translated in PHP structures <ul n: if="$items"> <li n: foreach="$items as $item">{$item|capitalize}</li> </ul> Value filtering Alternative syntax for if statement {if ($user)} <h 2>User {$user->login}</h 2> Name: {$user->name} Home page: <a n: href="$user->homepage">{$user->homepage}</a> {/if} Context-aware escaping by Martin Kruliš (v 1. 2) 20. 3. 2018 24
Controller/Presenter � Controller/Presenter ◦ One class that represents one (logical) page ◦ Multiple actions �Each action is a method �Rendering actions �Initialize a template, produce HTML (JSON, XML, …) �Other actions (POST actions) �Update model and respond with redirect �Careful when using POST actions for AJAX calls ◦ Naming convention for classes and methods �Has to reflect routing protocol by Martin Kruliš (v 1. 2) 20. 3. 2018 25
Security � Authentication ◦ Verifies identity of a user �E. g. , by user credentials, by a certificate, … ◦ User identity must be held despite statelessness �In a (secured) session, in a cookie, … ◦ Password security �Password should not be stored in plain text nor in decryptable form in the database, but rather hashed �<salt>, hashfnc(<salt>, <password>) �The hashfnc could be SHA-256, SHA-512, bcrypt, scrypt, … �PHP has built-in functions for password hashing �crypt(), password_hash(), password_verify() old by Martin Kruliš (v 1. 2) 20. 3. 2018 26
HTTP Authentication � Authentication Embedded in HTTP ◦ If the auth. information are provided, they are in �$_SERVER['PHP_AUTH_USER'] �$_SERVER['PHP_AUTH_PW'] ◦ The script can request authentication data header('WWW-Authenticate: Basic realm="Auth test"'); header('HTTP/1. 0 401 Unauthorized'); exit; ◦ Potential problems �Password is sent with every request �Logout operation is not very well defined by Martin Kruliš (v 1. 2) 20. 3. 2018 27
Security Tokens � Authentication/Access Tokens ◦ Generated once the user is authenticated ◦ Does not have to be private �Server can verify them (e. g. , using cryptography) ◦ For instance, a security token can be �user_id: salt: hash(user_id: salt: secret) �Where secret is known only to the server � JSON Web Tokens (JWT) RFC 7519 Crypto. hash is the signature ◦ Standard for implementing access tokens ◦ Data are base 64 encoded JSON ◦ HMAC SHA 256 is used for signature by Martin Kruliš (v 1. 2) Example 20. 3. 2018 28
Authorization � Authorization ◦ Process of verification access rights of the user ◦ Security Model �Defines protected objects, authorities, operations �Simple (state-less) models �Function (object, authority, operation) -> yes/no �More complex models exist �Typically implemented in one class (component) ◦ Roles �Authorities are typically not individual users, but roles �Each user have one (or multiple) roles by Martin Kruliš (v 1. 2) 20. 3. 2018 29
Authorization � Security Models Examples ◦ Directory (Capability List) �Authorities have lists of accessible objects ◦ Access List �Protected objects have lists of users (+permissions) ◦ Access Control Matrix �Rows ~ authorities, cols ~ objects, items ~ access rights ◦ Bell-La Padula �Each authority has maximal level of access, each object has minimal required level of access by Martin Kruliš (v 1. 2) 20. 3. 2018 30
Authorization � Access Control List (ACL) Example authorizator: setup: - add. Role('user') - add. Role('editor', 'user') - add. Role('admin', 'editor ') - add. Resource('Homepage') - add. Resource('Archive') Authorities (roles) Protected objects (resources) corresponds to controllers here - add. Resource('Users') - allow('user', 'Homepage', 'default') - allow('user', 'Archive', 'default') - allow('user', 'Users', 'show') - allow('editor', 'Users', 'show-private ') List of all access privileges (what is not explicitly allowed, is denied) - allow('editor', 'Archive', 'create') - allow('editor', 'Archive', 'edit') - allow('editor', 'Archive', 'delete') - allow('admin') Admin is allowed everything by Martin Kruliš (v 1. 2) 20. 3. 2018 31
Discussion by Martin Kruliš (v 1. 2) 20. 3. 2018 32
- Slides: 32