Home Security Spring Security 3.x Cookbook

Spring Security 3.x Cookbook

By Anjana Mankale
books-svg-icon Book
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$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!
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
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
    Basic Security
About this book
Web applications are exposed to a variety of threats and vulnerabilities at the authentication, authorization, service, and domain object levels. Spring Security can help secure these applications against those threats. Spring Security is a popular application security solution for Java applications. It is widely used to secure standalone web applications, portlets, and increasingly REST applications. It is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications and it is currently used to secure numerous demanding environments including government agencies, military applications, and central banks. "Spring Security 3.x Cookbook" is a repository of recipes to help you successfully secure web applications against threats and vulnerabilities at the authentication and session level layers using the Spring Security framework. We will not only explore Spring-based web applications, but also Java-based and Grails-based applications that can use Spring Security as their security framework. Apart from conventional web applications, we will also look at securing portlets, RESTful web service applications, and other non-web applications. This book will also take you through how to integrate Spring Security with other popular web frameworks/technologies such as Vaadin, EJB, and GWT. In addition to testing and debugging the implemented security measures, this book will also delve into finer aspects of Spring Security implementation such as how it deals with concurrency, multitenancy, and customization, and we will even show you how to disable it. This book gives you an overview of Spring Security and its implementation with various frameworks. It starts with container-based authentication before taking you on a tour of the main features of Spring Security. It demonstrates security concepts like BASIC, FORM, and DIGEST authentication and shows you how to integrate the Spring Security framework with various frameworks like JSF, struts2, Vaadin, and more. The book also demonstrates how to utilize container managed security without JAAS. Then, we move on to setting up a struts2 application before showing you how to integrate Spring Security with other frameworks like JSF, Groovy, Wicket, GWT, and Vaadin respectively. This book will serve as a highly practical guide and will give you confidence when it comes to applying security to your applications. It's packed with simple examples which show off each concept of Spring Security and which help you learn how it can be integrated with various frameworks.
Publication date:
November 2013
Publisher
Packt
Pages
300
ISBN
9781782167525

 

Chapter 1. Basic Security

In this chapter we will cover:

  • JAAS-based security authentication on JSPs

  • JAAS-based security authentication on servlet

  • Container-based basic authentication on servlet

  • Form-based authentication on servlet

  • Form-based authentication with open LDAP and servlet

  • Hashing/Digest Authentication on servlet

  • Basic authentication for JAX-WS and JAX-RS

  • 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.

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:

  • 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.

  • Form-based authentication: In this technique the container handles the authentication, but the login form is provided by the user as a JSP page.

  • Digest-based authentication: In this method user credentials are hashed with certain algorithms.

  • 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:

<xsd:element name="security-constraint" type="j2ee:security-constraintType"/>
<xsd:element name="login-config" type="j2ee:login-configType"/>
<xsd:element name="security-role "type="j2ee:security-roleType"/>

Getting ready

You will need the following to demonstrate authentication and authorization:

  • JBoss 7

  • Eclipse Indigo 3.7

  • Create a dynamic web project and name it Security Demo

  • Create a package, com.servlets

  • Create an XML file in the WebContent folder, jboss-web.xml

  • 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" %>
    <html >
      <HEAD>
        <TITLE>PACKT Login Form</TITLE>
        <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();
          }
        </SCRIPT>
      </HEAD>
      <BODY>
        <FORM name="myform" action="SecurityCheckerServlet" METHOD=get>
        <TABLE width="100%" border="0" cellspacing="0" cellpadding="1" bgcolor="white">
        <TABLE width="100%" border="0" cellspacing="0" cellpadding="5">
        <TR align="center">
        <TD align="right" class="Prompt"></TD>
        <TD align="left">
          <INPUT type="text" name="j_username" maxlength=20>
        </TD>
        </TR>
        <TR align="center">
        <TD align="right" class="Prompt"> </TD>
        <TD align="left">
        <INPUT type="password"name="j_password" maxlength=20 >
        <BR>
        <TR align="center">
        <TD align="right" class="Prompt"> </TD>
        <TD align="left">
        <input type="submit" onclick="javascript:submitForm();" value="Login">
        </TD>
        </TR>
        </TABLE>
        </FORM>
      </BODY>
    </html>

    The j_username and j_password are the indicators of using form-based authentication.

  2. Let's modify the web.xml file to protect all the files that end with .jsp. If you are trying to access any JSP file, you would be given a login form, which in turn calls a SecurityCheckerServlet file to authenticate the user. You can also see role information is displayed. Update the web.xml file as shown in the following code snippet. We have used 2.5 xsd. The following code needs to be placed in between the webapp tag in the web.xml file:

    <display-name>jaas-jboss</display-name>
     <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
     </welcome-file-list>
    
     <security-constraint>
        <web-resource-collection>
         <web-resource-name>something</web-resource-name>
         <description>Declarative security tests</description>
         <url-pattern>*.jsp</url-pattern>
         <http-method>HEAD</http-method>
         <http-method>GET</http-method>
         <http-method>POST</http-method>
         <http-method>PUT</http-method>
         <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
         <role-name>role1</role-name>
        </auth-constraint>
        <user-data-constraint>
         <description>no description</description>
         <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
     </security-constraint>
     <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
         <form-login-page>/login.jsp</form-login-page>
         <form-error-page>/logoff.jsp</form-error-page>
        </form-login-config>
     </login-config>
     <security-role>
        <description>some role</description>
        <role-name>role1</role-name>
     </security-role>
     <security-role>
        <description>packt managers</description>
        <role-name>manager</role-name>
     </security-role>
     <servlet>
        <description></description>
        <display-name>SecurityCheckerServlet</display-name>
        <servlet-name>SecurityCheckerServlet</servlet-name>
        <servlet-class>com.servlets.SecurityCheckerServlet</servlet-class>
     </servlet>
     <servlet-mapping>
        <servlet-name>SecurityCheckerServlet</servlet-name>
        <url-pattern>/SecurityCheckerServlet</url-pattern>
     </servlet-mapping>
  3. JAAS Security Checker and Credential Handler: Servlet is a security checker. Since we are using JAAS, the standard framework for authentication, in order to execute the following program you need to import org.jboss.security.SimplePrincipal and org.jboss.security.auth.callback.SecurityAssociationHandle and add all the necessary imports. In the following SecurityCheckerServlet, we are getting the input from the JSP file and passing it to the CallbackHandler.

    We are then passing the Handler object to the LoginContext class which has the login() method to do the authentication. On successful authentication, it will create Subject and Principal for the user, with user details. We are using iterator interface to iterate the LoginContext object to get the user details retrieved for authentication.

    In the SecurityCheckerServlet Class:

    package com.servlets;
    public class SecurityCheckerServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
         
        public SecurityCheckerServlet() {
          super();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           char[] password = null;
           PrintWriter out=response.getWriter();
           try
           {
              
             SecurityAssociationHandler handler = new SecurityAssociationHandler();
             SimplePrincipal user = new SimplePrincipal(request.getParameter("j_username"));
             password=request.getParameter("j_password").toCharArray();
             handler.setSecurityInfo(user, password);
             System.out.println("password"+password);
        
             CallbackHandler myHandler = new UserCredentialHandler(request.getParameter("j_username"),request.getParameter("j_password"));
             LoginContext lc = new LoginContext("other", handler);
             lc.login();
        
             Subject subject = lc.getSubject();
             Set principals = subject.getPrincipals();
            
             List l=new ArrayList();
             Iterator it = lc.getSubject().getPrincipals().iterator();
             while (it.hasNext()) {
               System.out.println("Authenticated: " + it.next().toString() + "<br>");
               out.println("<b><html><body><font color='green'>Authenticated: " + request.getParameter("j_username")+"<br/>"+it.next().toString() + "<br/></font></b></body></html>");
                  }
               it = lc.getSubject().getPublicCredentials(Properties.class).iterator();
               while (it.hasNext()) System.out.println(it.next().toString());
          
               lc.logout();
           }     catch (Exception e) {
                 out.println("<b><font color='red'>failed authenticatation.</font>-</b>"+e);
                
           }
        }
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       }
    
    }

    Create the UserCredentialHandler file:

    package com.servlets;
    class UserCredentialHandler implements CallbackHandler {
      private String user, pass;
    
      UserCredentialHandler(String user, String pass) {
        super();
        this.user = user;
        this.pass = pass;
      }
      @Override
      public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
          for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
              NameCallback nc = (NameCallback) callbacks[i];
              nc.setName(user);
            } else if (callbacks[i] instanceof PasswordCallback) {
              PasswordCallback pc = (PasswordCallback) callbacks[i];
              pc.setPassword(pass.toCharArray());
            } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
          }
        }
      }
     }

    In the jboss-web.xml file:

    <?xml version="1.0" encoding="UTF-8"?>
    <jboss-web>
    <security-domain>java:/jaas/other</security-domain>
    </jboss-web>

    Other is the name of the application policy defined in the login-config.xml file.

    All these will be packed in as a .war file.

  4. Configuring the JBoss Application Server. Go to jboss-5.1.0.GA\server\default\conf\login-config.xml in JBoss. If you look at the file, you can see various configurations for database LDAP and a simple one using the properties file, which I have used in the following code snippet:

    <application-policy name="other">
      <!-- A simple server login module, which can be used when the number of users is relatively small. It uses two properties files:
      users.properties, which holds users (key) and their password (value).
      roles.properties, which holds users (key) and a comma-separated list of
      their roles (value).
      The unauthenticatedIdentity property defines the name of the principal
      that will be used when a null username and password are presented as is
      the case for an unauthenticated web client or MDB. If you want to allow such users to be authenticated add the property, e.g.,
        unauthenticatedIdentity="nobody"
      -->
      <authentication>
      <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
        flag="required"/>
        <module-option name="usersProperties">users.properties</module-option>
        <module-option name="rolesProperties">roles.properties</module-option>
        <module-option name="unauthenticatedIdentity">nobody</module-option> 
      </authentication>
    </application-policy>
  5. Create the users.properties file in the same folder. The following is the Users.properties file with username mapped with role.

    User.properties

    anjana=anjana123

    roles.properties

    anjana=role1
  6. Restart the server.

Tip

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.

How it works...

JAAS consists of a set of interfaces to handle the authentication process. They are:

  • The CallbackHandler and Callback interfaces

  • The LoginModule interface

  • LoginContext

The CallbackHandler interface gets the user credentials. It processes the credentials and passes them to LoginModule, which authenticates the user.

JAAS is container specific. Each container will have its own implementation, here we are using JBoss application server to demonstrate JAAS.

In my previous example, I have explicitly called JASS interfaces.

UserCredentialHandler implements the CallbackHandler interfaces.

So, CallbackHandlers are storage spaces for the user credentials and the LoginModule authenticates the user.

LoginContext bridges the CallbackHandler interface with LoginModule. It passes the user credentials to LoginModule interfaces for authentication:

CallbackHandler myHandler = new UserCredentialHandler(request.getParameter("j_username"),request.getParameter("j_password"));
  LoginContext lc = new LoginContext("other", handler);
  lc.login();

The web.xml file defines the security mechanisms and also points us to the protected resources in our application.

The following screenshot shows a failed authentication window:

The following screenshot shows a successful authentication window:

See also

  • The JAAS-based security authentication on servlet recipe

  • The Container-based basic authentication on servlet recipe

  • The Form-based authentication on servlet recipe

  • The Form-based authentication with open LDAP and servlet recipe

  • The Hashing/Digest Authentication on servlet recipe

  • The Basic authentication for JAX-WS and JAX-RS recipe

  • The Enabling and disabling the file listing recipe

 

JAAS-based security authentication on servlet


The JAAS-based security authentication on servlet is an extension of JAAS-based security authentication for JSPs. In this section, we are demonstrating that we can even apply security on servlets.

Getting ready

  • Create a new Web Project in Eclipse

  • Create a package, com.packt.security.servlets

  • Create a Servlet with name ProtectedServlets

How to do it...

The following are the steps for JAAS-based security for servlet:

  1. Create a servlet and name it ProtectedServlets:

    public class ProtectedServlets extends HttpServlet {
      private static final long serialVersionUID = 1L;
        
      public ProtectedServlets() {
        super();
           
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        try
        {
          out.println("Hello User");
          out.println("Authtype:"+request.getAuthType());
          out.println("User Principal:"+request.getUserPrincipal());
          out.println("User role:"+request.isUserInRole("role1"));
        }
        catch (Exception e) {
          out.println("<b><font color='red'>failed authenticatation</font>-</b>"+e);
    
        }
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
      }
    
    }
  2. Now, edit the web.xml file to secure the servlet:

    <web-resource-collection>
    <web-resource-name>Servlet Protection</web-resource-name>
    <description>Declarative security tests</description>
    <url-pattern>/ProtectedServlets</url-pattern>
    <http-method>HEAD</http-method>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
    <http-method>PUT</http-method>
    <http-method>DELETE</http-method>
    </web-resource-collection>

How it works...

Restart the server and access the URL: http://localhost:8080/jaas-jboss/ProtectedServlets.

You would get a login form, which will authenticate the user. The servlet is the protected resource, and anyone accessing the servlet will be asked to log in. The authentication is handled by JAAS API, which is application-server-specific. Each application server will have its own implementation of security.

See also

  • The Container-based basic authentication on servlet recipe

  • The Form-based authentication on servlet recipe

  • The Form-based authentication with open LDAP and servlet recipe

  • The Hashing/Digest Authentication on servlet recipe

  • The Basic authentication for JAX-WS and JAX-RS recipe

  • The Enabling and disabling the file listing recipe

 

Container-based basic authentication on servlet


In our previous examples we used interfaces provided by JAAS to authenticate with loginform.jsp. The previous application had a custom login form design with authentication handled by JAAS API provided by the application server.

Getting ready

  • Create a simple web-app project

  • Create a servlet class

  • Edit the web.xml file for basic authentication

  • Add a constraint to restrict the user from accessing the servlet

How to do it...

Now, we will see the basic authentication. The container provides the login form and authenticates the user and redirects the user to the servlet after authentication is successful. There is no login form involved.

Make the following changes in the web.xml file:

<login-config>
   <auth-method>BASIC</auth-method>
<form-login-config>  

Export the .war to JBoss, restart the server, and access the servlet.

How it works...

In the previous example the container decides the mechanism for authenticating the servlet by reading the web.xml file. Here the <auth-method> tag has defined BASIC as the mode of authentication. We should get a login dialog box popped up when we access the secured resource.

The following screenshots show the workflow of the implementation:

See also

  • The Form-based authentication on servlet recipe

  • The Form-based authentication with open LDAP and servlet recipe

  • The Hashing/Digest Authentication on servlet recipe

  • The Basic authentication for JAX-WS and JAX-RS recipe

  • The Enabling and disabling the file listing recipe

 

Form-based authentication on servlet


In the previous sections, we demonstrated the basic authentication on servlets and JSPs. Now let's use form-based authentication on servlets.

Getting ready

Let's apply form-based authentication on servlet. You will need a simple web application with a servlet, a web container to handle the authentication, and the web.xml file that tells the container what to authenticate.

How to do it...

Let's see some simple steps for implementing form-based authentication on servlets:

  1. Create a JSP file named Containerform.jsp:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <form method="POST" action="j_security_check">
    Username:<input type="text" name="j_username">
    password:<input type="password" name="j_password">
    <input type=submit>
    </form>
    </body>
    </html>

    What do you observe in the previous code?

    action=j_security_check is the default URL, which is recognized by the web container. It tells the container that it has the user credentials to be authenticated.

  2. Now, edit the web.xml file:

    <login-config>
      <auth-method>FORM</auth-method>
      <form-login-config>
        <form-login-page>/Containerform.jsp</form-login-page>
        <form-error-page>/logoff.jsp</form-error-page>
      </form-login-config>
    </login-config>

Build the project and export the .war files to JBoss.

How it works...

The previous example demonstrated the Form-based authentication. The J2EE container reads the web.xml file, the <auth-method> tag has the form attribute set. Then it further looks for the login.jsp file, which needs to be displayed to do form-based authentication. The <form-error-page> and <form-login-page> has the login file name and the error page that needs to be displayed on authentication failure. When the user tries to access the secured resource, the J2EE container redirects the request to the login page. The user credentials are submitted to j_security_check action. This action is identified by the container and does the authentication and authorization; on success the user is redirected to the secured resource and on failure the error page shows up.

The following are the screenshots of the workflow which shows the login page for the user and displays the user information on successful authentication:

See also

  • The Form-based authentication with open LDAP and servlet recipe

  • The Hashing/Digest Authentication on servlet recipe

  • The Basic authentication for JAX-WS and JAX-RS recipe

  • The Enabling and disabling the file listing recipe

 

Form-based authentication with open LDAP and servlet


In this section we will see how we can authenticate users by retrieving the user information stored in open LDAP and JAAS. Open LDAP, as its name suggests, is a free version of the lightweight user directory protocol, which allows us to create groups and add users to it.

Getting ready

Download open LDAP, create roles, groups, and user.

In the JBoss application server, edit the login-config.xml file.

How to do it...

Perform the following steps to configure the application server to retrieve users from Open LDAP:

  1. In the login-config.xml file provide the LDAP port with the URL, credentials, and the domain that needs to be searched to find the username and password provided by the application:

    <application-policy name="example">
     <authentication>
     <login-module code="org.jboss.security.auth.spi.LdapExtLoginModule" flag="required" >
     <module-option name="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</module-option>
     <module-option name="java.naming.provider.url">ldap://localhost:389</module-option>
     <module-option name="java.naming.security.authentication">simple</module-option>
     <module-option name="bindDN">cn=Manager,dc=maxcrc,dc=com</module-option>
     <module-option name="bindCredential">secret</module-option>
     <module-option name="baseCtxDN">ou=People,dc=maxcrc,dc=com</module-option>
     <module-option name="baseFilter">(uid={0})</module-option>
    
     <module-option name="rolesCtxDN">ou=Roles,dc=maxcrc,dc=com</module-option>
      <module-option name="rolesCtxDN">ou=Department,dc=maxcrc,dc=com</module-option>
     <module-option name="roleFilter">(member={1})</module-option>
     <module-option name="roleAttributeID">cn</module-option>
     <module-option name="searchScope">ONELEVEL_SCOPE</module-option>
     <module-option name="allowEmptyPasswords">true</module-option>
     </login-module>
    </authentication>
    </application-policy>
  2. In the jboss-web.xml file, we will specify the lookup name for JAAS:

    jboss-web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <jboss-web>
    <security-domain>java:/jaas/example</security-domain>
    </jboss-web>

How it works...

Build and deploy the WAR on JBoss, restart the server, and access the browser.

You will be prompted with a login form and JBoss authenticates the user based on the open LDAP credentials provided. The user is retrieved and is authorized with roles mentioned in the application policy. The container provides built-in APIs for authentication. The module org.jboss.security.auth.spi.LdapExtLoginModule handles the LDAP authentication process.

See also

  • The Hashing/Digest Authentication on servlet recipe

  • The Basic authentication for JAX-WS and JAX-RS recipe

  • The Enabling and disabling the file listing recipe

 

Hashing/Digest authentication on servlet


In the previous authentication mechanisms, the client sends the user credentials and the container validates.

The client doesn't attempt to encrypt the password.

So, our application is still not safe and is vulnerable to attacks.

This section is about passing an encrypted user credential to the server and telling the server which encryption algorithm can be used to decrypt the data.

JBoss is the application server that I have chosen to demonstrate it.

Getting ready

  • Modify Login-config.xml

  • Create encrypt-users. properties

  • Create encrypt-roles. properties

How to do it....

  1. Modify the web.xml file:

    <login-config>
        <auth-method>DIGEST</auth-method>
        <realm-name>PACKTSecurity</realm-name>
    </login-config>
  2. Now, modify the jboss-web.xml file. The realm name is used for hashing:

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- <jboss-web> -->
    <!-- <security-domain>java:/jaas/other</security-domain> -->
    <!-- </jboss-web> -->
    <jboss-web>
    <security-domain>java:/jaas/encryptme</security-domain>
    </jboss-web>
  3. Modify the login-config.xml file

    <application-policy name="encryptme">
        <!--this is used to demonstrate DIGEST Authentication
        -->
        <authentication>
          <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
            flag="required"/>
        <module-option name="usersProperties">encrypt-users.properties</module-option>
        <module-option name="rolesProperties">encrypt-roles.properties</module-option>
        <module-option name="hashAlgorithm">MD5</module-option>
        <module-option name="hashEncoding">rfc2617</module-option>
        <module-option name="hashUserPassword">false</module-option>
        <module-option name="hashStorePassword">true</module-option>
        <module-option name="passwordIsA1Hash">true</module-option>
       <module-option name="storeDigestCallback">
                    org.jboss.security.auth.spi.RFC2617Digest
        </module-option>	
        </authentication>
      </application-policy>
  4. Now, we need to tell JBoss to encrypt the user's password. To do that perform the following steps:

    • Go to E:\JBOSS5.1\jboss-5.1.0.GA\common\lib

    • Open jbosssx-server.jar

    • Go to the folder where JBoss is installed. I have installed JBoss on my E:

    • Now on the command line, write cd E:\JBOSS5.1\jboss-5.1.0.GA>

    • And then paste the following command: java -cp client/jboss-logging-spi.jar;common/lib/jbosssx-server.jar org.jboss.security.auth.spi.RFC2617Digest anjana "PACKTSecurity" role1

    • Now edit Encrypt-users. properties:

      anjana=e3b6b01ec4b0bdd3fc1ff24d0ccabf1f
    • Encrypt roles and update roles.properties

How it works...

The previous example demonstrates the digest authentication mechanism. The password given in the J2EE container is encrypted using the MD5 algorithm. The container decrypts it and verifies the user credentials against the decrypted password. The authentication mechanism is digest and the container pops up a login dialog box for the digest mechanism similar to the basic authentication mechanism.

The following screenshot shows the workflow:

It behaves like basic authentication, but uses the encrypted password along with the realm name to decrypt.

See also

  • The Basic authentication for JAX-WS and JAX-RS recipe

  • The Enabling and disabling the file listing recipe

 

Basic authentication for JAX-WS and JAX-RS


The authentication configuration remains the same for JAX-WS and JAX-RS.

We need to give the JAX-WS or JAX-RS URL in <web-resource collection>.

Auth_type can be basic. The container would come with a form for the user to enter the username and password.

Authentication handled by container

We will first create a web service and then make the container handle the security on it.

Let's create an interface which will expose the service method and then declare an implementation class.

Let's use Tomcat 6.0 to demonstrate this.

Getting ready

  • In Eclipse-Indigo, create a dynamic web project

  • Server: Tomcat 6

  • JARs to be added to Tomcat lib folder: https://jax-ws.java.net/2.2.7/

  • Download the project and copy the lib folder

How to do it...

  1. Create an interface and an implementation class. Add the @WebService annotations to it. Create a package named com.packt.ws. Create an interface named EmployeeProfile and an implementation Class:

    Interface:

    package com.packt.ws;
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    import javax.jws.soap.SOAPBinding;
    import javax.jws.soap.SOAPBinding.Style;
    @WebService
    @SOAPBinding(style = Style.RPC)
    public interface EmployeeProfile {
      @WebMethod
      String getSalary();
    }

    Implementation:

    package com.packt.ws;
    import javax.jws.WebService;
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    @WebService(endpointInterface = "com.packt.ws.EmployeeProfile")
    public class EmployeeProfileImpl implements EmployeeProfile {
             @Override
    public String getSalary() {
        return "no salary for the month";
    }
    }
  2. Also add the sun-jaxws.xml file under WEB-INF

    <?xml version="1.0" encoding="UTF-8"?>
    <endpoints
      xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
      version="2.0">
      <endpoint
          name="EmployeeProfile"
          implementation="com.packt.EmployeeProfileImpl"
          url-pattern="/employee"/>
    </endpoints>
  3. Modify the web.xml file as shown:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>JAX-WS-Authentication-Tomcat</display-name>
       <listener>
            <listener-class>
               com.sun.xml.ws.transport.http.servlet.WSServletContextListener
            </listener-class>
        </listener>
        <servlet>
            <servlet-name>employee</servlet-name>
            <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>employee</servlet-name>
            <url-pattern>/employee</url-pattern>
        </servlet-mapping>
       <security-role>
         <description>Normal operator user</description>
         <role-name>operator</role-name>
       	</security-role>
     
    <security-constraint>
          <web-resource-collection>
            <web-resource-name>Operator Roles Security</web-resource-name>
            <url-pattern>/employee</url-pattern>
          </web-resource-collection>
     
          <auth-constraint>
            <role-name>operator</role-name>
          </auth-constraint>
          <user-data-constraint>
              <transport-guarantee>NONE</transport-guarantee>
          </user-data-constraint>
       </security-constraint>
     
    <login-config>
          <auth-method>BASIC</auth-method>
       </login-config>
     
    </web-app>
  4. Authenticate the web services. Edit the tomcat-users.xml file and add this to server.xml:

    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                 resourceName="UserDatabase"/>

How it works...

By accessing the following URL, you should be prompted for a login.

Each web service URL is authenticated.

You will be prompted with a login page (http://localhost:8080/EmployeeProfile/employee)

See also

  • The Enabling and disabling the file listing recipe

 

Enabling and disabling the file listing


It's generally not advisable to enable directory listing in your application. By default directory listing will be disabled on JBoss.

If it is enabled, go to your JBoss installation folder.

How to do it...

The following steps will help to disable and enable file listing in the application server:

  1. Browse to the path \server\default\deployers\jbossweb.deployer.

  2. Open web.xml in the WEB-INF folder.

  3. Set the listing to false.

    <servlet>
          <servlet-name>default</servlet-name>
          <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
          <init-param>
             <param-name>debug</param-name>
             <param-value>0</param-value>
          </init-param>
          <init-param>
             <param-name>listings</param-name>
             <param-value>false</param-value>
          </init-param>
          <load-on-startup>1</load-on-startup>
       </servlet>

See also

  • The Spring Security with Struts2 recipe

About the Author
  • Anjana Mankale

    Anjana Mankale is a tech lead and has 8 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 Struts2. 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 cloud-based multitenant applications. Anjana has also authored a cookbook, Spring Security 3.x Cookbook, Packt Publishing. Anjana is passionate about blogging (http://jtechspace.blogspot.in/), where she shares her write-ups and technical code that she has worked on.

    Browse publications by this author
Spring Security 3.x Cookbook
Unlock this book and the full library FREE for 7 days
Start now