📄 Page
1
www.it-ebooks.info
📄 Page
2
RESTful Java Web Services Security Secure your RESTful applications against common vulnerabilities René Enríquez Andrés Salazar C. BIRMINGHAM - MUMBAI www.it-ebooks.info
📄 Page
3
RESTful Java Web Services Security Copyright © 2014 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: July 2014 Production reference: 1180714 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78398-010-9 www.packtpub.com Cover image by Vivek Thangaswamy (vivekthangaswamy@yahoo.com) www.it-ebooks.info
📄 Page
4
Credits Authors René Enríquez Andrés Salazar C. Reviewers Erik Azar Ismail Marmoush Debasis Roy Acquisition Editor Vinay Argekar Content Development Editor Adrian Raposo Technical Editor Shruti Rawool Copy Editor Sayanee Mukherjee Project Coordinators Melita Lobo Harshal Ved Proofreaders Simran Bhogal Paul Hindle Indexers Hemangini Bari Rekha Nair Graphics Abhinash Sahu Production Coordinator Arvindkumar Gupta Cover Work Arvindkumar Gupta www.it-ebooks.info
📄 Page
5
About the Authors René Enríquez is currently a software architect for a multinational company headquartered in India. He has previously worked on many projects related to security implementation using frameworks such as JAAS and Spring Security to integrate many platforms based on the Web, BPM, CMS, and web services for government and private sector companies. He is a technology and innovation enthusiast, and he is currently working with several programming languages. He has achieved the following certifications: • Oracle Certified Professional, Java SE 6 Programmer • Microsoft Technology Associate • Cisco Network Operating Systems Over the past few years, he has worked as a software consultant on various projects for private and government companies and as an instructor of courses to build enterprise and mobile applications. He is also an evangelist of best practices for application development and integration. Andrés Salazar C. is currently working at one of the most prestigious government companies in Ecuador, performing tasks related to software development and security implementation based on JAAS and digital signatures for secure applications. He also has extensive knowledge of OAuth implementation on web projects. He is a technology and Agile enthusiast, and he has worked on several projects using the JEE technology and TDD. He has achieved the following certifications: • Oracle Certified Professional, Java SE 6 Programmer • Certified Scrum Developer www.it-ebooks.info
📄 Page
6
About the Reviewers Erik Azar is a professional software developer with over 20 years of experience in the areas of system administration, network engineering and security, development, and architecture. Having worked in diverse positions in companies ranging from start-ups to Fortune 500 companies, he currently works as a REST API architect for Availity, LLC in Jacksonville, FL. He is a dedicated Linux hobbyist who enjoys kernel hacking while experimenting with Raspberry Pi and BeagleBone Black boards. In his spare time, he works on solutions using embedded microprocessor platforms, Bluetooth 4.0, and connects to the cloud using RESTful APIs. Ismail Marmoush is a Java and Machine Learning Certified Expert. He has published the open source projects RESTful Boilerplates for IAAS and PAAS (GAE), an artificial neural network framework, and crawlers/dataminers and some language code examples. You can find more about him, his work, and his tutorials on his personal blog (http://marmoush.com). Thanks to my family and the Packt Publishing team. www.it-ebooks.info
📄 Page
7
Debasis Roy is working as the Team Lead / Scrum Master of the sports team for Vizrt Bangladesh based at Dhaka. He has 7 years of professional working experience as a software engineer in Java/C++-relevant technologies. He has been working at Vizrt for the past 5 years. He started his journey here with a product called the Online Suite, also known as Escenic Content Engine/Studio, and he is now continuing with products related to Viz Sports. Vizrt provides real-time 3D graphics, studio automation, sports analysis, and asset management tools for the broadcast industry—interactive and virtual solutions, animations, maps, weather forecasts, video editing, and compositing tools. Previously, he worked at SDSL/AfriGIS for 2 years, where he was involved mainly in the projects, Marbil and Grid. AfriGIS is a technology innovation company that creates geographic information and communication solutions. www.it-ebooks.info
📄 Page
8
www.PacktPub.com Support files, eBooks, discount offers, and more You might want to visit www.PacktPub.com for support files and downloads related to your book. 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 www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, 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. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. www.it-ebooks.info
📄 Page
9
www.it-ebooks.info
📄 Page
10
This book is dedicated to my wife and son, who supported me through so many days and nights of work and gave me their love and support; my brother, who has always lent me his support; my father, who has been an example of struggle and tireless work; my mother, who has always been concerned about me and has supported me throughout life, gracias mami; and finally, my great friends, who have always been supportive of me. René Enríquez I dedicate this book to my family. It is because of the work and love of my parents that I have had the chance to study and become a professional software engineer, and because of the support and love of my sisters that I want to keep improving myself. Also, I want to dedicate this book to my grandmother, Mariana, who is the strongest person in the world. Muchas gracias abuelita! Finally, I dedicate the book to my bear man, Steve, for his support and English lessons. Andrés Salazar C. www.it-ebooks.info
📄 Page
11
www.it-ebooks.info
📄 Page
12
Table of Contents Preface 1 Chapter 1: Setting Up the Environment 7 Downloading tools 7 Downloading links 8 Creating the base project 8 First functional example 13 Testing the example web service 18 Summary 20 Chapter 2: The Importance of Securing Web Services 21 The importance of security 22 Security management options 23 Authorization and authentication 24 Authentication 24 Authorization 24 Access control 25 Transport layer security 25 Basic authentication by providing user credentials 26 Digest access authentication 32 An example with explanation 32 Authentication through certificates 37 API keys 41 Summary 44 Chapter 3: Security Management with RESTEasy 45 Fine-grained and coarse-grained security 46 Securing HTTP methods 49 HTTP method – POST 50 HTTP method – GET 51 www.it-ebooks.info
📄 Page
13
Table of Contents [ ii ] Fine-grained security implementation through annotations 55 The @RolesAllowed annotation 55 The @DenyAll annotation 59 The @PermitAll annotation 60 Programmatical implementation of fine-grained security 60 Summary 62 Chapter 4: RESTEasy Skeleton Key 63 OAuth protocol 64 OAuth and RESTEasy Skeleton Key 64 What is RESTEasy Skeleton Key? 64 OAuth 2.0 authentication framework 64 Main features 65 OAuth2 implementation 66 Updating RESTEasy modules in JBoss 66 Setting up the configuration in JBoss 67 Implementing an OAuth client 67 SSO configuration for security management 77 OAuth token via Basic Auth 79 Running the application 81 Custom filters 82 Server-side filters 83 Client-side filters 84 Example usage of filters 84 Summary 90 Chapter 5: Digital Signatures and Encryption of Messages 91 Digital signatures 92 Updating RESTEasy JAR files 94 Applying digital signatures 96 Testing the functionality 100 Validating signatures with annotations 103 Message body encryption 112 Testing the functionality 114 Enabling the server with HTTPS 115 Testing the functionality 120 Summary 123 Index 125 www.it-ebooks.info
📄 Page
14
Preface The inherent advantages of the use of web services in computer systems development are the same that create the need for security management over them. Today, we can say that no company is able to work in complete isolation, without the need to interact with others and share and consume information. Furthermore, this is the most important asset of any company. For this reason, these requirements are also common between lines of code. This book presents real scenarios with applicable solutions, leading you by the hand all the way, so you can easily learn solutions and implementations that will resolve the most common needs that can arise. RESTful web services offer several advantages over those based on SOAP. For example, when handling data types, depending on the programming language or the libraries you use to create them, you can find inconsistencies when using empty values ("") instead of NULL. Also, you may find difficulties in mapping complex objects and compatibility issues in file transferring when using different versions of libraries to create/consume the web service. In certain situations, even when consuming a web service created in Java from a .NET application, it ends up creating a service implemented in Java in the middle of both. This does not occur in RESTful web services, since in this case, the functionality is exposed through HTTP method invocations. In order to protect information, the world of securities has many features that help to achieve this. For example, understanding how some issues such as authentication and authorization assist in the implementation of any selected mechanism, where the main objective is to make our applications safer and secure, is essential. The selection of each of the different ways to secure applications goes along with the problem you want to resolve; for this, we show usage scenarios for each of them. Many times, we have seen large organizations spend time and effort in creating their own implementations to handle securities rather than using the standard that has already resolved what we need. Through the knowledge that we want to share with you, we hope to avoid this process of reinventing the wheel. www.it-ebooks.info
📄 Page
15
Preface [ 2 ] What this book covers Chapter 1, Setting Up the Environment, helps us create our first functional application, something very similar to a Hello World example, but with some more functionality and very close to the real world. The main aim of this chapter is to familiarize ourselves with the tools we are going to use. Chapter 2, The Importance of Securing Web Services, goes through all possible models of authentication in the Java platform. For your better understanding, we will go step by step and dive deep into how we can leverage each available authentication model. We will show you how the information is exposed and how it can be intercepted by third parties, and we will play with Wireshark, which is a very good tool to explain it. Finally, in this chapter, we will review the differences between authentication and authorization. Both concepts are very important and definitely impossible to put aside in the context of securities terms. Chapter 3, Security Management with RESTEasy, shows how RESTEasy offers mechanisms to handle security, starting from a fairly basic model (coarse-grained) to a more elaborate one (fine-grained) in which you can perform more exhaustive controls, including managing not only configuration files, but also programmatical files. Chapter 4, RESTEasy Skeleton Key, helps us study the OAuth implementation along with the token bearer implementation and Single Sign-On. All of them are used in order to limit the way the resources are shared. As always, you will get hands-on with code and real examples. We want to show you how sharing resources and information between applications through these technologies has turned into one of the most useful and powerful techniques by allowing clients or users to use their credentials only once to access several services, limiting the access to third-party applications to your information or data, and implementing access control through the token bearer. You will learn to apply these technologies and concepts in order to build secure and flexible applications. Chapter 5, Digital Signatures and Encryption of Messages, helps us understand the benefits of digital signatures using a simple example; you'll notice how the message's receiver can validate the identity of the sender. In addition, we will simulate when an external agent modifies data in transit and see how digital signatures can help us to detect it, in order to avoid working with corrupted data. Finally, we will explain SMIME for body encryption and how it works, with an example that encrypts requests and responses for your better understanding. www.it-ebooks.info
📄 Page
16
Preface [ 3 ] What you need for this book In order to implement and test all the examples in this book, we will use many free tools, such as the following: • Eclipse IDE (or any other Java IDE) • JBoss AS 7 • Maven • Wireshark • SoapUI Who this book is for This book is intended for developers, software analysts, architects, or people who work with software development and RESTful web services. This book requires some previous knowledge of object-oriented programming concepts in Java or any other language. No previous knowledge on security models is required because we explain the theory and apply it on practical examples in this book. Conventions In this book, you will find a number of styles of text 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, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We are going to modify the web.xml file." A block of code is set as follows: private boolean isUserAllowed(final String username, final String password, final Set<String> rolesSet) { boolean isAllowed = false; if (rolesSet.contains(ADMIN)) { isAllowed = true; } return isAllowed; } } www.it-ebooks.info
📄 Page
17
Preface [ 4 ] When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: final List<String> authorizationList = headersMap.get(AUTHORIZATION_ PROPERTY); Any command-line input or output is written as follows: mvn clean install New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "From the pop-up window, select the SSL Settings tab." Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback as suggestions or comments from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of and also to improve the way we transmit knowledge. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via 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 on 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. www.it-ebooks.info
📄 Page
18
Preface [ 5 ] Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Also, we highly suggest obtaining the source code from GitHub available at https://github.com/restful-java-web-services-security. 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 would 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 http://www.packtpub. com/submit-errata, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Piracy Piracy of copyright 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 copyright@packtpub.com 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 You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it. www.it-ebooks.info
📄 Page
19
www.it-ebooks.info
📄 Page
20
Setting Up the Environment We extend you a very warm welcome to the first chapter of our journey. Let's give you an idea of what you will achieve here. After reading this chapter, you will have the basic and stimulating knowledge you need to set up a development environment to work with RESTful web services. Then, you will familiarize yourself with the development of a very basic project related to it. In addition, by the end, you will have a very clear idea of how to create applications using RESTful web services and how you can achieve this. This chapter will give you the information you need to work with web services of this kind in a very easy and comprehensive way. In this chapter, we will cover the following topics: • Installing the development environment • Creating our first RESTful web services application • Testing the RESTful web service Downloading tools First, we must obtain our work tools so that we get our hands into code. Tools specified here are used around the world, but you are free to choose your tools. Remember, "Tools do not make the artist". It doesn't matter if you use Windows, MAC OS X, or Linux; tools are available for every OS. Let's explain briefly what each tool is for. We will develop the examples using Eclipse as our IDE, JBoss AS 7.1.1.Final as our application server, Maven to automatize the build process, and SoapUI as a tool to test the functionality of web services that we will create. In addition, we suggest that you should install the latest version of JDK, which is JDK 1.7.x. For help, we have obtained and included some links that you need to use to get the software to implement the first example. Each link gives you more information about each tool, which can be profitable as you learn something about each one if you don't know about them already. www.it-ebooks.info