Home Application-development Spring Security Essentials

Spring Security Essentials

By Nanda Nachimuthu
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Spring Security
About this book

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is how easily it can be extended to meet custom requirements. The popularity of the Spring framework is increasing and the security package of Spring addresses vast mechanisms of Security in a rich way. Due to an increasing number of applications for various business needs, the integration of multiple applications is becoming inevitable. The standard security procedures available across multiple implementations in Spring will protect vulnerable applications that are open to larger public and private audiences.

Spring Security Essentials focuses on the need to master the security layer, which is an area not often explored by a Spring developer.

At the beginning, we’ll introduce various industry standard security mechanisms and the practical ways to integrate with them. We will also teach you about some up-to-date use cases such as building a security layer for RESTful web services and applications.

The IDEs used and security servers involved are briefly explained, including the steps to install them. Many sample projects are also provided to help you practice your newly developed skills. Step-by-step instructions will help you master the security layer integration with the Server, then implement the experience gained from this book in your own real-time application.

Publication date:
January 2016
Publisher
Packt
Pages
164
ISBN
9781785282621

 

Chapter 1. Getting Started with Spring Security

When we talk about enterprise security, three major areas of security—authentication, authorization, and access control list (ACL)—will play a major role. The Spring Framework 4.0.3 has a seven-layered architecture that includes a core container, context, Aspect-Oriented Programming (AOP), Data Access Object (DAO), Object-relational mapping (ORM), Web, and Model-View-Controller (MVC). To provide security features to all these layers, we have The Spring Security 3.2.3 module, which will provide security facilities such as user authentication and authorization, role-based authorization, database configuration, password encryption, and others.

In general, Spring developers focus on the seven layers to develop the web applications, and most of them will not be able to master the security mechanisms involved in different layers with different implementations as they might have to call the abstract programs in which the security implementations are built.

Spring 3.2.3 supports various authentication approaches for different industry standard connectivity for Java EE-based enterprise applications. Many people use Spring Security in the layers of Java EE's Servlet Specification and Enterprise Java Beans (EJB) Specification, which will limit the usage of proper Spring Security implementations. Due to this, many enterprise security scenarios are left unattended. Authentication is the process of creating a principal in the enterprise system for which a user needs to provide credentials. The role-based access privileges will be decided on a predefined role authorizer system from which the core system will read the access rights for the given principal. The advanced techniques of the Spring Security mechanisms are as follows:

  • Custom user realms

  • Custom authorization constraints

  • Method-based authorization

  • Instance-based authorization

  • Building a security layer for RESTful web services

The following modules of Spring 3.2.3 support the implementation of enterprise security:

  • Spring Security Core

  • Spring Security remoting

  • Spring Security Web

  • Spring Security configuration

  • Spring Security LDAP

  • Spring Security ACL

  • Spring Security CAS

  • Spring Security OpenID

Additionally, we will cover specific techniques such as JavaServer Faces (JSF) 2.0, Wicket, and Java Authentication and Authorization Service (JAAS). The following are the new security features provided in Spring 4.0, which we will talk about later:

  • Web socket support

  • Test support

  • Spring data integration

  • Cross-Site Request Forgery (CSRF) token argument resolver

  • Secure defaults

Most of these authentication levels are from third parties or developed by relevant standard bodies such as Internet Engineering Task Force (IETF). Spring Security has its own authentication features that will be useful to establish connections securely with third-party request headers, protocols, and single sign-on systems. We will have a detailed description of each system and mechanism in the following chapters.

 

Spring custom user realms


Custom security realms facilitate you to use an existing data store such as a directory server or database when authenticating and authorizing users to enterprise applications, which are deployed in a standard application server, such as WebSphere, JBoss, and so on. We will have to provide the attribute details to the server to create the user realms such as the name, realm class name, configuration data, and password. We can create a custom realm by providing a custom JAAS login module class and custom realm class. However, when we use the client-side JAAS login modules, this may not be suitable for use with the enterprise server.

There can be two different realms that cater to two different URL patterns. We can use the same authentication logic for both the realms. The standard Spring Security mechanism will invoke j_spring_security_check automatically when a login form is getting called, and we can define our own URLs that are to be intercepted. This approach is called browser-based client security realm. If the user has not been provided with a username and password and if the principal is not created to access this URL, then the user will be redirected to the login page by the Spring Security checker.

 

Spring custom authorization constraints


There are many types of security constraints. This consists of web resource collections such as URL patterns, HTTP methods, and authorization constraints by providing role names. User data constraints such as web requests are passed over an authenticated transport. A security constraint is used to define the access privileges for a collection of resources using their URL mapping. The security token will be given from an HTTPS request when it gets validated and will be given back to the enterprise application server. There may be possibilities that the security token does not return any valid roles for authorization.

In these scenarios, we will have to set the security authorization constraints in a secured way in the web.xml file. The web resources can have unchecked access, checked access, and no access. We can omit the authorization constraints so that any web resource can access the resource. We can specify the role name for the authorization constraint so that only these roles can access the web resource. We can also exclude a set of web resources from accessing any request by specifying no roles for these resources. We can also exclude particular URLs to access the specific secured web resources.

 

Spring method-based authorization


Method security is a bit more complicated than a simple allow or deny rule. Custom methods can be provided with specific security settings. In Spring, we can achieve this by providing the proper annotations for the methods to be secured. There are four annotations that support expression attributes to allow preinvocation and post-invocation authorization checks and also support the filtering of the submitted collection arguments or return values. They are @PreAuthorize, @PreFilter, @PostAuthorize, and @PostFilter. If you want to create a custom secured method called customCheckUser(), then you can annotate the method with the @PreAuthorize tag for a presecurity check before execution.

While the other security methods focus on servlets and controllers, security method-based authorization deals with the service layer components particularly. We can control various services to be accessed by specific principals. For example, an administrative principal can access only the database credential layer or the logging layer can be accessed by all the principals. The global method security tag or the @EnableGlobalMethodSecurity annotation will help developers in setting up the method level security.

 

Spring instance-based authorization


At the class level, we can check whether the intended principal is authorized to invoke the particular instance or not when we create an instance for a particular request. This can be achieved by providing annotations before instantiating the object in order to check the authenticity. This instance-based security is important in handling non-application server-related code or any other code related to the business logic that needs to be closely monitored to prevent non-privileged access.

The approach here is to define the information clearly so that the domain object-based security restrictions can be applied accurately. The Actor who is performing the use case action, the domain acted created internally to perform the action, and the intended action are the three pieces of information that we need to define clearly in order to achieve instance-based authorization. Here comes the usage of ACLs and access control entries (ACEs), which will be elaborated on in further chapters. The advantage of using Spring ACL and ACE here is that Spring has an internal mechanism to manage the ACE volume by implementing the ACE inheritance mechanism so that when a number of domain objects increases, the ACEs also will become manageable.

Note

Apart from these techniques, Spring provides you with options to build a security layer for RESTful and SOAP web services, and we can create security layers for JAAS, JSF 2.0, and Wicket. Let's take a quick look at these four techniques now.

 

Spring Security with SOAP web services


Spring Web Services (Spring-WS) packages focus mainly on the creation of document-driven web services, where the data communication between web services is done through XML envelopes and web services can be accessed from any other technology application server. The features supported by Spring-WS are powerful XML mappings, support for various XML APIs, flexible XML marshalling, support for WS-Security, and others. WS-Security comprises of three areas—authentication, digital signatures, and encryption/decryption.

The security flow in Spring Web Services will be as follows. The system will generate a security token for a valid principal using a separate web service method. If the user wants to access other web services, he or she should pass this token along with the payload as a security key and these web services will validate this token for authenticity and then allow the users to access the resources. If the token has expired or is invalid, the user should go through the authentication web service once again. This entire mechanism is called message signing.

 

Spring Security with RESTful web services


To achieve Representational State Transfer (REST) services calls with basic security authentication, we will have to depend on the libraries provided by the Spring framework, such as the core, configuration, and web. We also need to make some entries in the Spring application context files.

In real-time scenarios, we will have to get the credentials from Lightweight Directory Access Protocol (LDAP), Database, and others.

 

Spring Security with JSF2.0


Coming to the JSF and Spring Security integration, the Spring web flow provides you with a JSF integration that simplifies the handshake between JSF and Spring. A dedicated Spring Security tag library is available for JSF Security integration. To achieve this, springsecurity.taglib.xml needs to be updated with facelet entries. These modifications must be reflected in web.xml as well. We can include nested contents based on security conditions using the authorize tags. During JSF rendering, many expression language-based functions can be used.

 

Spring Security with Wicket


Apache Wicket is designed based on a component-oriented structure and less HTML file handling. Wicket-related security settings must be handled first by modifying the web.xml file for the corresponding filter mapping. As a Wicket programmer, you will need to have a clear understanding about the pull and push concepts and form processing life cycle of the Apache Wicket framework. There are two unique issues to be handled from Wicket. Wicket does not manage the life cycle of its components, and the components and models of Wicket are often serialized, which may be an issue for Spring's dependency injection mechanism. The work around this will be some entries in the Web and ApplicationContext XML files, but this approach will have its own pros and cons, which we will discuss later.

 

Spring Security with JAAS


The Spring framework has a JAAS authentication provider, which must be configured in an applicationcontext.xml file. We need to create an array of entries for the URLs that need to be secured. We have to define the security policies for different URLs of the website. JAAS will expect a callback from the user—the username and password. Spring will have this information collected and populated on an authentication object, which will be passed to JAAS as an input.

 

Spring Security with SAML


Security Assertion Markup Language (SAML) is a popular open standard, which simplifies federated user logins. A user can provide credentials to a centralized enterprise registry, and using this principal, the user can access other independent applications that are mapped with the centralized registry.

This is called single sign-on implementation using the Spring and SAML integration. We can also create a common setup to make an enterprise an single sign-on (SSO)-enabled one with the following certain standards. This is based on how we set up Spring and SAML to pass the SAML tokens to the other applications that are using the SSO. We can create a shared cookie that will contain the authorized SAML token. Additionally, we can develop an internal SAML token verifier, which may frequently assess the validity of the token. The securityContext XML file needs to be updated with the IDP metadata. IDP is nothing but the centralized Identity provider.

 

Spring Security with LDAP


You must be aware of the LDAP basics, and you can refer to a popular open source LDAP implementation called OpenLDAP if you want to further explore. Spring has an LDAP package that is helpful in accessing many LDAP implementations without bothering much about their internals. This is developed based on the JdbcTemplate package design. Basic operations such as looking up, context initiation and closing, iterating through the results, and encoding/decoding the values are taken care of by this package. On top of this, Spring LDAP comes with various enhanced features such as LDAP template, LDAP context, LDAP filters, LDAP transaction management, and others.

 

Summary


We have seen the various flavors of the Spring Security implementations available in the Spring Framework 4.0.3 along with the Spring 3.2.3 module. We will explore each of these options in detail with practical examples in the coming chapters. We recommend that you have a good understanding of the application development environment for various technologies that we will address, such as LDAP, SAML, Wicket, and so on. In the next chapters, we will explain the security implementations that include the basics of the IDE setup, understanding a sample source code, building mechanisms, and so on.

About the Author
  • Nanda Nachimuthu

    Nanda Nachimuthu (dxbnanda) works as a Principal Architect with Emirates Airlines, Dubai.

    He has 20 years of experience in IT, which includes 13 years as an architect in various technologies such as J2EE, SOA, ESB, Cloud, Big Data,GIS,Mobility and IoT. He has designed, architected, and delivered many national and large-scale commercial projects. He is also involved in design and development of various products in the insurance, finance, energy, logistics, and life sciences domains.

    Browse publications by this author
Spring Security Essentials
Unlock this book and the full library FREE for 7 days
Start now