CORS Essentials - Rajesh Gunasundaram - E-Book

CORS Essentials E-Book

Rajesh Gunasundaram

0,0
27,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book explains how to use CORS, including specific implementations for platforms such as Drupal, WordPress, IIS Server, ASP.NET, JBoss, Windows Azure, and Salesforce, as well as how to use CORS in the Cloud on Amazon AWS, YouTube, Mulesoft, and others. It examines limitations, security risks, and alternatives to CORS. It explores the W3C Specification and major developer documentation sources about CORS. It attempts to predict what kinds of extension to the CORS specification, or completely new techniques, will come in the future to address the limitations of CORS
Web developers will learn how to share code and assets across domains with CORS. They will learn a variety of techniques that are rather similar in their method and syntax. The book is organized by similar types of framework and application, so it can be used as a reference. Developers will learn about special cases, such as when a proxy is necessary. And they will learn about some alternative techniques that achieve similar goals, and when they may be preferable to using CORS

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 164

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

CORS Essentials
Credits
About the Authors
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Why You Need CORS
The same-origin policy
Considering the origin of entities
Internet Explorer exception policy
Commonly allowed cross-origin resource sharing
DOM elements allowed for cross-origin sharing
Allowing cross-origin sharing in WebSockets
Limited cross-origin JavaScript API access
Permissions required by JavaScript
JavaScript data storage access is strictly limited by origin
How CORS works – the header and the request
The CORS header
Example 1 – CORS request with JavaScript
Passing a request to a utility function
Example 2: the CORS transaction to retrieve the title tag
Distributing DOM elements to multiple domains
Putting it all together
Securing when all domains are whitelisted
Methods to add security when a CORS header whitelists all domains
Simple CORS request methods
CORS with Preflight
Triggering a preflight by setting a custom header
The preflight request
The preflight response
CORS via jQuery
Known issues with CORS preflight
Preflight in Firefox
Preflight in Chrome
Preflight in Internet Explorer
Non-simple CORS request methods and headers require preflight
Checking for the withCredentials property
Troubleshooting and debugging CORS
Browser support for crossorigin attribute in the <script> tag
CORS with jQuery
jQuery CORS AJAX plugin
Enabling CORS globally with server configuration
Alternatives to CORS
Example of JSON-P
Using JSON-P – limitations and risks
Proposed JSON-P validation standard
WebSocket
WebSocket handshakes
WebSocket and cross-domain resource sharing
Risks of using WebSocket for cross-domain resource sharing
The window.postMessage method
postMessage risks and security measures
Summary
2. Creating Proxies for CORS
Proxies and the World Wide Web
What is a proxy server?
Reasons to use a proxy
Avoid mixing up protocols
Some API platforms require proxies or CORS
Getting through a local network firewall
Types of proxy server
Creating a proxy server with Google App Engine
Reverse proxy server
Reverse proxy server with Apache VirtualHost and .htaccess
Reverse proxy server in node.js
Summary
3. Usability and Security
CORS usability
Browser support for CORS
Detecting AJAX support in the browser
Using preflight for non-simple CORS requests
The HTTP request headers
HTTP response headers
Enhancing security in CORS
Limiting access when using the Access-Control-Allow-Origin, * wildcard
Trusting the HTTP_ORIGIN header is not recommended
Requests with credentials
CORS security cheat sheet by OWASP
Summary
4. CORS in Popular Content Management Frameworks
Incoming CORS requests
SAAS or self-hosted?
CORS in WordPress
Limited support for CORS in SAAS WordPress.com
Unauthenticated GET requests to WordPress.com
Authenticated requests to WordPress.com
CORS in self-hosted WordPress
Adding the Access-Control-Allow-Origin header in a template
WordPress plugins for CORS
WP-CORS plugin for WordPress
Allow CORS XML-RPC plugin for WordPress
CORS in Drupal
Enabling CORS in Drupal with custom code
Using the drupal_add_http_header function
Adding CORS support with .htaccess
Adding the CORS headers with custom code
Drupal contributed modules for CORS
Drupal CORS module
Drupal CDN module
Drupal Amazon S3 CORS upload module
CORS in Drupal 8 core
CORS in Joomla!
setHeader in JApplication web
matware-libraries on GitHub
Allowing CORS in the .htaccess file
CORS in Adobe Experience Manager
The com.adobe.cq.social.commons.cors package
Methods in the CORSAuthenticationFilter class
Methods In the CORSConfig class
Methods in the CORSAuthInfoPostProcessor class
Adding CORS headers in Scene 7 with a ruleset
Configuring the Sling Referrer Filter in the CRX Console
Summary
5. CORS in Windows
Incoming CORS requests
How to set the Access-Control-Allow-Origin header globally in Windows IIS Server
Setting CORS headers globally with web.config for IIS7 Server
Setting CORS headers globally with IIS manager for IIS 8.5 and higher
CORS in the ASP.NET Web API
Enabling CORS in the ASP.NET Web API
Installing the Web API Cross-Origin Support Package
Enabling the CorsMessageHandler
The EnableCorsAttribute class sets the CORS policies
Configuring the EnableCors class attributes in the ASP.NET Web API
Example: setting CORS policy for HTTP methods GET, PUT, and POST
Setting CORS policy with wildcards
Example: Setting CORS policy globally with wildcards
Example: Setting a global CORS policy with the WebApiConfig class
Disallowing CORS in classes or methods
Example: Using explicit values for HTTP methods
Example: Using the DisableCors attribute
Dynamic ASP.NET Web API CORS policies
Custom CORS policy attribute classes
Example: A custom CORS policy class
Custom policy provider factory
Registering the DynamicPolicyProviderFactory in WebApiConfig
Example: A custom CORS policy provider factory
Debugging the ASP.NET Web API Cross-Origin support framework
Server-side debugging
Client-side debugging
CORS in Windows Communication Foundation
CORS in Windows browsers – Internet Explorer and Edge
Summary
6. CORS in the Cloud
CORS requests in cloud APIs
CORS in Amazon Simple Storage Service (S3)
Scenarios for needing CORS in Amazon S3
How to enable CORS on an S3 bucket
Elements in an S3 CORSRule
AllowedOrigin element (required)
AllowedMethod element (required)
AllowedHeader element (optional, required for preflight)
MaxAgeSeconds element (optional)
ExposeHeader element (optional)
CORSConfiguration CORSRules with required elements
CORSConfiguration CORSRule with optional elements
How does Amazon S3 evaluate the CORS Configuration on a bucket?
Using CORS in Google Cloud Storage
Configuring CORS on a bucket in Google Cloud Storage
Using gsutil cors set in Google Cloud Storage
Using the XML API in Google Cloud Storage
Getting CORS configuration for a bucket with the XML API
Putting a CORSConfig on a bucket with the XML API
Troubleshooting CORS-related problems in Google Cloud Storage
Problems with headers
Problems with cached preflight requests
Problems with the resumable upload protocol
Authenticated access to Google APIs with CORS
Google API Keys
Adding the Google API client library for JavaScript
The Google API CORS request
Authenticated CORS requests to Google APIs with OAuth
Example using the Authorization request header
Example using the access_token in the URL parameter
CORS in IBM Cloudant
How to GET or PUT a CORS configuration in IBM Cloudant
How to GET a CORS Configuration
Set or Modify a CORS Configuration
Security considerations when CORS in IBM Cloudant
CORS in Windows Azure Storage
CORS usage scenarios for Windows Azure Storage
CORS for Windows Azure Blobs (file uploads)
CORS for Windows Azure Table
Preflight requests in Windows Azure
Code examples for CORS in Windows Azure
Static CORS rules in Windows Azure
Dynamically configuring CORS in Windows Azure
Enabling CORS on a Windows Azure Storage account for the blob (file) service
JavaScript code for uploading an image to a Windows Azure Storage Blob service with CORS in ASP.NET
CORS on a Windows Azure Storage account for the table service
CORS in Box API
CORS in the Dropbox API
Summary
References
7. CORS in Node.js
JavaScript frameworks are very popular
Introduction to Node.js
JavaScript frameworks that work with Node.js
Express.js is a Node.js server framework
AngularJS extends static HTML with dynamic views
Connect.js provides middleware for Node.js requests
Backbone.js often uses a Node.js server
ReactJS handles user interfaces
Socket.IO uses WebSockets for real-time, event-driven applications
Ember.js can use Node.js
CORS in Express.js
CORS npm for Express.js using Connect.js middleware
Configuration options for CORS npm
Code examples for CORS npm
Enable CORS globally for all origins and all routes
Allowing CORS for dynamic origins for a specific route
Enabling CORS preflight
Configuring CORS asynchronously
CORS in AngularJS
Enabling CORS in AngularJS
Making a CORS request in AngularJS
CORS in Backbone.js
Using Backbone.CrossDomain to modify Backbone.sync
How to proxy Backbone.sync for cross-domain requests
jQuery Ajax needs to use the XHR Header
Ember.js also relies on CORS-enabled jQuery AJAX
Socket.IO manages origins for security
Node.js and JavaScript frameworks are evolving rapidly
Summary
References
8. CORS Best Practices
Enabling API to public CORS requests
Limiting API to allow CORS requests to a whitelisted set of origins
Protecting against cross-site request forgery (CSRF)
Minimizing preflight requests
Summary
Index

CORS Essentials

CORS Essentials

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2017

Production reference: 1220517

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78439-377-9

www.packtpub.com

Credits

Authors

Rajesh Gunasundaram

Randall Goya

Commissioning Editor

Wilson D'souza

Acquisition Editor

Tushar Gupta

Content Development Editor

Aishwarya Pandere

Technical Editor

Dharmendra Yadav

Copy Editor

Manisha Sinha

Project Coordinator

Nidhi Joshi

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Tania Dutta

Production Coordinator

Shraddha Falebhai

Cover Work

Shraddha Falebhai

About the Authors

Rajesh Gunasundaram is a software architect, technical writer, and blogger. He has over 15 years of experience in the IT industry, with more than 10 years using Microsoft .NET, 2 years of BizTalk Server, and a year of iOS application development.

Rajesh is a founder and editor of technical blogs and , where you can find many of his technical writings on .NET and iOS.

Rajesh is also the founder and developer of a web product, a platform that analyses YouTube videos and channels.

Rajesh has also written a book ASP.NET Web API Security Essentials, for Packt Publishing.

Rajesh holds a masters degree in Computer Application and began his career as a software engineer in 2002. He worked on client premises located in various countries, such as the UK, Belarus, and Norway. He also has experience in developing mobile applications for iPhone and iPad.

His technical strengths include Azure, Xamarin, ASP.NET MVC, Web API, WCF, .NET Framework/.NET Core, C#, Objective-C, Angular, BizTalk, SQL Server, REST, SOA, design patterns, and software architecture.

Randall Goya has been a Senior Web Developer and Application Architect for enterprise organizations for several years, mostly specializing as a Drupal Consultant. Drupal as a framework is integrated with so many other applications and APIs, including payment gateways, media (Brightcove, YouTube, mp3, and video players), messaging (Amazon SQS, Mulesoft), as a content repository for other frameworks (WordPress), and for native mobile applications, and VOIP.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At , you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1784393770.

If you'd like to join our team of regular reviewers, you can e-mail us at <[email protected]>. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Preface

This book will explain how to use CORS, including specific implementations for platforms such as Drupal, WordPress, IIS server, ASP.NET, JBoss, Windows Azure, and Salesforce, as well as how to use CORS in the Cloud on Amazon AWS, YouTube, Mulesoft, and others. It will examine the limitations, security risks, and alternatives to CORS. It will examine the W3C specification and major developer documentation sources about CORS. It will predict what kind of extensions to the CORS specification, or completely new techniques, may come in the future to address the limitations of CORS.

What this book covers

Chapter 1, Why You Need CORS, discusses the same-origin policy, which limits sharing resources across domains; granting access to CORS requests by setting headers; different ways to add more security; understanding preflight requests to prepare for some types of CORS methods and events; and alternatives to CORS.

Chapter 2, Creating Proxies for CORS, discusses what a Proxy Server is and various reasons to use a Proxy, different types of Proxy Servers, and reverse proxis in Node.js with CORS anywhere.

Chapter 3, Usability and Security, discusses CORS and XDomainRequest, detecting AJAX support in the browser, using preflight to ensure usability and improve security, handling access-control-allow-origin header with and without the wildcard, HTTP request and response headers for usability and security, CORS requests with credentials, and setting and reading cookies, and CORS security cheat sheet by OWASP.

Chapter 4, CORS in Popular Content Management Frameworks, discusses how to enable CORS in WordPress, Drupal, Joomla!, and Adobe Experience Manager (AEM).

Chapter 5, CORS in Windows, discusses implementing CORS on the Windows platform. The Windows platform includes IIS, ASP.NET Web API applications, and Windows Communication Foundation.

Chapter 6, CORS in the Cloud, discusses using CORS in cloud computing services such as Amazon Simple Storage Service (S3), Google Cloud Storage, IBM Cloudant, Windows Azure Storage, the Box.com API, and the Dropbox API.

Chapter 7, CORS in Node.js, discusses the Node.js platform and using CORS in JavaScript frameworks such as ReactJS, Ember.js, and Socket.IO, with examples based on the fundamentals of CORS with allowed origin(s), methods, and headers.

Chapter 8, CORS Best Practices, discusses best practices in enabling API-to-public CORS requests, limiting the API to allow CORS requests to a whitelisted set of origins, protecting against cross-site request forgery (CSRF), and minimizing preflight requests.

What you need for this book

Any good JavaScript editorWamp, Lamp, or Xamp, depending on the devlopment platform environmentIIS to host the ASP.NET applicationVisual Studio 2012 or later to develop the ASP.NET Web API

Who this book is for

This book is intended for any web developer who works on various web applications with different technologies, developers who create APIs for external applications to consume, and developers who ensure security when cross-origin resource sharing happens.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles are shown as follows: "Media files with the <video> and <audio> tags as long as the file type matches expected media formats."

A block of code is set as follows:

public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Other configurations omitted config.EnableCors(); config.SetCorsPolicyProviderFactory( new DynamicPolicyProviderFactory()); } }

Any command-line input or output is written as follows:

PM> Install-Package Microsoft.AspNet.WebApi.Cors

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the books title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting , selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Why You Need CORS

In this chapter, you will learn about the following:

The same-origin policy that limits sharing resources across domainsGranting access to CORS requests by setting headersHow to do something with the responseText request from a CORS requestRudimentary security in CORS and ways to add more securityPreflight requests to prepare for some types of CORS methods and eventsEnabling the crossorigin attribute in a script tag for better troubleshootingAlternatives to CORS: JSON-P, WebSockets, and window.postMessage

The same-origin policy

Sooner or later, web developers run up against the same-origin policy. Maybe you want to trigger a script on one domain and use the results on a different domain, but you can't.

The same-origin policy is necessary for web application security. The execution of a script may expose sensitive information. Access to this information is limited to the same domain where the script is located, unless access for an external domain has been specifically allowed by code.

Note

The same-origin policy is defined by the Internet Engineering Task Force (IETF) (https://tools.ietf.org/html/rfc6454#page-4).

A major motivation for implementing the same-origin policy is to protect sensitive information stored in cookies from being exposed to another domain. Web applications maintain authenticated user sessions in cookies. The user's personalizations and account information are stored in cookies. To ensure data confidentiality, cookies may not be shared across domains. For cookies, the same origin is shared by the domain or a sub-domain of that domain. For DOM elements such as scripts, the restrictions are more fine-grained.

The same-origin policy