Spring Security 3.x Cookbook
Over 60 recipes to help you successfully safeguard your web applications with Spring Security
Anjana Mankale
BIRMINGHAM - MUMBAI
Spring Security 3.x Cookbook Copyright © 2013 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 author, 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: November 2013
Production Reference: 1171113
Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78216-752-5 www.packtpub.com
Cover Image by Aniket Sawant (
[email protected])
Credits Author Anjana Mankale Reviewers Laurent Frisée Michael Waluk Acquisition Editor Kevin Colaco Lead Technical Editor Balaji Naidu Technical Editors Aman Preet Singh Chandni Maishery Shali Sasidharan Tarunveer Shetty
Project Coordinator Wendell Palmar Proofreader Bernadette Watkins Indexer Priya Subramani Graphics Ronak Dhruv Production Coordinator Aparna Bhagat Cover Work Aparna Bhagat
About the Author Anjana Mankale is a Tech Lead with 7 years of experience in developing web applications. She has developed applications for healthcare, e-commerce portals, media portals, and content management systems using Spring and Struts 2. She is extensively involved in application design and implementation. She has worked on Amazon cloud and Spring web services and has recently been involved in deploying and designing a cloud-based multitenant application. Anjana is passionate about blogging (http://jtechspace.blogspot.in/) where she shares her write-ups and technical code that she has worked on. I would like thank Mr. Dharanidhara Mishra who is a Senior Solution Architect and has been guiding me on application security. I would also like to thank my husband, Raghavendra S., for his complete support and encouragement by intimating on the timelines. Lastly I would like to thank my parents and in-laws for their encouragement in completing this book.
About the Reviewers Laurent Frisée is a freelance consultant with 13 years of experience working for well
known as well as less well known companies. He has been a Java developer for the last 10 years and has been involved in the architecture development of the software most of this time. In recent years, he has focused on Java persistence-related problems and is looking forward to working with new technologies (like GWT) or enterprise solutions (like ESB).
Michael Waluk has over 20 years of experience developing secure, scalable software-as-aservice web applications. He has leveraged Spring Security since it was open-sourced as Acegi Security in 2004, securing both large and small enterprise projects with it and extending most of its features. Today, millions of people are using these applications to do business securely.
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
[email protected] 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? ff
Fully searchable across every book published by Packt
ff
Copy and paste, print and bookmark content
ff
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.
Table of Contents Preface 1 Chapter 1: Basic Security 7 Introduction 7 JAAS-based security authentication on JSPs 8 JAAS-based security authentication on servlet 17 Container-based basic authentication on servlet 19 Form-based authentication on servlet 21 Form-based authentication with open LDAP and servlet 23 Hashing/Digest authentication on servlet 25 Basic authentication for JAX-WS and JAX-RS 28 Enabling and disabling the file listing 32
Chapter 2: Spring Security with Struts 2
33
Chapter 3: Spring Security with JSF
65
Introduction 33 Integrating Struts 2 with Spring Security 35 Struts 2 application with basic Spring Security 41 Using Struts 2 with digest/hashing-based Spring Security 43 Using Spring Security logout with Struts 2 46 Authenticating databases with Struts 2 and Spring Security 49 Getting the logged-in user info in Struts 2 with Spring Security 53 Displaying custom error messages in Struts 2 for authentication failure 57 Authenticating with ApacheDS with Spring Security and Struts 2 application 59 Introduction 65 Integrating JSF with Spring Security 66 JSF with form-based Spring Security 74 JSF and form-based authentication using Spring Security to display logged-in user 80
Table of Contents
Using JSF with digest/hashing-based Spring Security Logging out with JSF using Spring Security Authenticating database with Spring Security and JSF ApacheDS authentication with JSF and Spring Security Authentication error message with JSF and Spring Security
Chapter 4: Spring Security with Grails
82 85 90 92 94
97
Introduction 97 Spring Security authentication with Groovy Grails setup 97 Spring Security with Grails to secure Grails controller 102 Spring Security authentication with Groovy Grails logout scenario 104 Spring Security with Groovy Grails Basic authentication 106 Spring Security with Groovy Grails Digest authentication 108 Spring Security with Groovy Grails multiple authentication 112 Spring Security with Groovy Grails LDAP authentication 119
Chapter 5: Spring Security with GWT
125
Chapter 6: Spring Security with Vaadin
153
Chapter 7: Spring Security with Wicket
175
Introduction 125 Spring Security with GWT authentication using Spring Security Beans 126 Form-based authentication with GWT and Spring Security 141 Basic authentication with GWT and Spring Security 143 Digest authentication with GWT and Spring Security 145 Database authentication with GWT and Spring Security 147 LDAP authentication with GWT and Spring Security 150 Introduction 153 Spring Security with Vaadin – basic authentication 154 Spring Security with Vaadin – Spring form-based authentication 158 Spring Security with Vaadin – customized JSP form-based authentication 159 Spring Security with Vaadin – using Vaadin form 165 Introduction 175 Spring Security with Wicket – basic database authentication 177 Spring Security with Wicket – Spring form-based database authentication 182 Spring Security with Wicket – customized JSP form-based database authentication 184 Spring authentication with Wicket authorization 187 Multitenancy using Wicket and Spring Security 192
ii
Table of Contents
Chapter 8: Spring Security with ORM and NoSQL DB
199
Chapter 9: Spring Security with Spring Social
221
Chapter 10: Spring Security with Spring Web Services
239
Chapter 11: More on Spring Security
265
Introduction 199 Spring Security with Hibernate using @preAuthorize annotation 201 Spring Security with Hibernate using authentication provider with @preAuthorize annotation 206 Spring Security with Hibernate using UserDetailsService with Derby database 210 Spring Security with MongoDB 214 Introduction 221 Spring Security with Spring Social to access Facebook 221 Spring Security with Spring Social to access Twitter 226 Spring Security with multiple authentication providers 228 Spring Security with OAuth 232
Introduction 239 Applying Spring Security on RESTful web services 240 Spring Security for Spring RESTful web service using the cURL tool 244 Integrating Spring Security with Apache CXF RESTful web service 247 Integrating Spring Security with Apache CXF SOAP based web service 253 Integrating Spring Security with Apache Camel 260 Introduction 265 Spring Security with multiple authentication providers 265 Spring Security with multiple input authentications 267 Spring Security with Captcha integration 272 Spring Security with JAAS 276
Index 281
iii
Preface Introduction Spring Security is a security layer that comes with Spring framework. Spring framework is an active open source project which has made further development of the application easier. It provides various layers to handle different scenarios and challenges that we face during the design and implementation life cycle of the project. The Spring Security layer of Spring framework is very loosely coupled with the Spring framework, hence it can be easily integrated with other applications. In this book we will be integrating Spring Security with other frameworks and we will also demonstrate it with coded examples.
What this book covers Chapter 1, Basic Security, covers the basics of security in a J2ee application. It introduces to the reader the various mechanisms of applying security to authenticate and authorize the users to the application. It also explains container management security. Chapter 2, Spring Security with Struts 2, provides steps to integrate Spring Security in a Struts 2 application. It demonstrates database authentication and LDAP authentication and authorization with other security mechanism offered by Spring framework. Chapter 3, Spring Security with JSF, explains all the aspects of Spring Security with a JSF application. It shows how to make the JSF application communicate with Spring Security using listeners. Chapter 4, Spring Security with Grails, demonstrates how the grails application can seamlessly integrate with Spring Security. We have also shown how Spring Security UI offers screens to create users and roles. We have demonstrated the use of Spring Security tags in GSP pages.
Preface Chapter 5, Spring Security with GWT, focuses on the GWT framework. The GWT framework is integrated with GWT and Spring Security can be used to authenticate and authorize users accessing the GWT application. Chapter 6, Spring Security with Vaadin, puts forward various options for integrating Spring Security with the Vaadin framework. We have created a sample product catalog application to demonstrate Spring Security integration with the Vaadin framework. Chapter 7, Spring Security with Wicket, demonstrates the integration of the wicket framework with Spring Security. Wicket itself has an authentication and authorization framework inbuilt, but the challenge was to make wicket use an external framework for authentication and authorization. Chapter 8, Spring Security with ORM and NoSQL DB, explains Hibernate and MongoDB in authentication and authorization using Spring Security API classes. Chapter 9, Spring Security with Spring Social, introduces Spring Social, which is a framework developed by Spring Source to provide integration to social networking sites. Spring Social intern uses Spring Security to do the authentication and authorization. The chapter demonstrates how Spring Social and Spring Security integrate with each other by demonstrating a Facebook login application. Chapter 10, Spring Security with WebServices, explains various options to secure RESTFUL and SOAP based webservices. Chapter 11, More on Spring Security, is a miscellaneous chapter. It explains integrating Spring Security with the Kaptcha API and providing multiple input authentications.
What you need for this book In order to complete all the recipes in this book you will need an understanding of the following: ff
JBOSS server
ff
Netbeans
ff
Maven
ff
Java
ff
Tomcat
ff
Open LDAP
ff
Apache DS
ff
Eclipse IDE
2
Preface
Who this book is for This book is for all Spring-based application developers as well as Java web developers who wish to implement robust security mechanisms into web application development using Spring Security. Readers are assumed to have a working knowledge of Java web application development, a basic understanding of the Spring framework, and some knowledge of the fundamentals of the Spring Security framework architecture. Working knowledge of other web frameworks such as Grails and so on would be an added advantage to exploit the whole breadth of recipes provided in this book, but this is not mandatory.
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 are shown as follows: "We can include other contexts through the use of the include directive." A block of code is set as follows: <%@ page contentType="text/html; charset=UTF-8" %> <%@ page language="java" %>
PACKT Login Form <SCRIPT> function submitForm() { var frm = document. myform; if( frm.j_username.value == "" ) { alert("please enter your username, its empty"); frm.j_username.focus(); return ; }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: <%@ page contentType="text/html; charset=UTF-8" %> <%@ page language="java" %>
PACKT Login Form <SCRIPT> 3
Preface function submitForm() { var frm = document. myform; if( frm.j_username.value == "" ) { alert("please enter your username, its empty"); frm.j_username.focus(); return ; }
Any command-line input or output is written as follows: [INFO] Parameter: groupId, Value: com.packt [INFO] Parameter: artifactId, Value: spring-security-wicket [INFO] Parameter: version, Value: 1.0-SNAPSHOT
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: "After clicking on submit we need to get an authenticated session." Warnings or important notes appear in a box like this.
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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to
[email protected], and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
[email protected] 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.
4
Preface
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.
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.
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/support, 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
[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 You can contact us at
[email protected] if you are having a problem with any aspect of the book, and we will do our best to address it.
5
1
Basic Security In this chapter we will cover: ff
JAAS-based security authentication on JSPs
ff
JAAS-based security authentication on servlet
ff
Container-based basic authentication on servlet
ff
Form-based authentication on servlet
ff
Form-based authentication with open LDAP and servlet
ff
Hashing/Digest Authentication on servlet
ff
Basic authentication for JAX-WS and JAX-RS
ff
Enabling and disabling the file listing
Introduction Authentication and authorization has become a major part of all web applications. Authentication involves checking who is accessing the application. Authorization is a process of checking the access rights of the user. In the native approach, we usually store the user's information in the database and write the code in the application. We also create roles for the user and we do the mapping. Here, it is tightly coupled with the application because we have to rewrite the entire code when we connect to a new database or use any other tools such as LDAP or Kerbose. But there are advance options to handle authentication and authorization. J2EE container provides different ways to authenticate the user by configuring the XML files. We can classify authentication into two types, that is, the container-based authentication and authorization and application level authentication and authorization. J2EE container provides interfaces and classes to provide authentication. In this chapter, we can see how we authenticate the user using JAAS, basic authentication, and form-based authentication.
Basic Security In this book, we have used JAAS because it a standard framework for authentication. JAAS works on the PAM (pluggable authentication module) framework. Authentication and authorization can be provided in the following ways: ff
Basic authentication: In this technique the application server gives a login form with a username and password textbox, so you don't have to create a login page yourself. You will also know the caller identity.
ff
Form-based authentication: In this technique the container handles the authentication, but the login form is provided by the user as a JSP page.
ff
Digest-based authentication: In this method user credentials are hashed with certain algorithms.
ff
Certificate-based authentication: In this technique the client and the server exchange certificates to verify their identity. Achieving an SSL certificate makes the data transfer over the network secure.
JAAS-based security authentication on JSPs The deployment descriptor is the main configuration file of all the web applications. The container first looks out for the deployment descriptor before starting any application. The deployment descriptor is an XML file, web.xml, inside the WEB-INF folder. If you look at the XSD of the web.xml file, you can see the security-related schema. The schema can be accessed using the following URL: http://java.sun.com/xml/ns/ j2ee/web-app_2_4.xsd. The following is the schema element available in the XSD:
Getting ready You will need the following to demonstrate authentication and authorization: ff
JBoss 7
ff
Eclipse Indigo 3.7
ff
Create a dynamic web project and name it Security Demo
ff
Create a package, com.servlets
8
Chapter 1 ff
Create an XML file in the WebContent folder, jboss-web.xml
ff
Create two JSP pages, login.jsp and logoff.jsp
How to do it... Perform the following steps to achieve JAAS-based security for JSPs: 1. Edit the login.jsp file with the input fields j_username, j_password, and submit it to SecurityCheckerServlet: <%@ page contentType="text/html; charset=UTF-8" %> <%@ page language="java" %>
PACKT Login Form <SCRIPT> function submitForm() { var frm = document. myform; if( frm.j_username.value == "" ) { alert("please enter your username, its empty"); frm.j_username.focus(); return ; } if( frm.j_password.value == "" ) { alert("please enter the password,its empty"); frm.j_password.focus(); return ; } frm.submit(); }