Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Spring Security 3.x Cookbook
Spring Security 3.x Cookbook

Spring Security 3.x Cookbook: Secure your Java applications against online threats by learning the powerful mechanisms of Spring Security. Presented as a cookbook full of recipes, this book covers a wide range of vulnerabilities and scenarios.

eBook
₹799 ₹3276.99
Paperback
₹4096.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Spring Security 3.x Cookbook

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:

How it works...

The following screenshot shows a successful authentication window:

How it works...

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:

How it works...
How it works...

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:

How it works...
How it works...

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
      How to do it....
    • 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:

How it works...

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
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn about all the mandatory security measures for modern day applications using Spring Security
  • Investigate different approaches to application level authentication and authorization
  • Master how to mount security on applications used by developers and organizations

Description

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.

Who is this book 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.

What you will learn

  • Implement Form-based, HTTP Basic, Client, and Digest authentications
  • Bring in Groovy on Grails with Form-based Spring Security
  • Integrate Spring Security with Vaadin
  • Combine Spring Security with ORM and NoSQLDB
  • Use Spring Security in Spring-Social (Facebook and Twitter)
  • Learn about Spring Security for SOAP
  • Authenticate RESTful services with Spring Security

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 22, 2013
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781782167532
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 22, 2013
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781782167532
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 4,096.99
Spring Security 3.x Cookbook
₹4096.99
Total 4,096.99 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Basic Security Chevron down icon Chevron up icon
2. Spring Security with Struts 2 Chevron down icon Chevron up icon
3. Spring Security with JSF Chevron down icon Chevron up icon
4. Spring Security with Grails Chevron down icon Chevron up icon
5. Spring Security with GWT Chevron down icon Chevron up icon
6. Spring Security with Vaadin Chevron down icon Chevron up icon
7. Spring Security with Wicket Chevron down icon Chevron up icon
8. Spring Security with ORM and NoSQL DB Chevron down icon Chevron up icon
9. Spring Security with Spring Social Chevron down icon Chevron up icon
10. Spring Security with Spring Web Services Chevron down icon Chevron up icon
11. More on Spring Security Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(4 Ratings)
5 star 0%
4 star 75%
3 star 25%
2 star 0%
1 star 0%
John C. Gunvaldson Feb 18, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I received Spring Security 3.x Cookbook as an eBook from Packt Publishing about a month ago. This was fortunate as I had prior to this point been struggling implementing Spring Security into our new Spring MVC sample developer’s web application at work (ultimately to become our standard Maven Archetype for new web development).The requirements at work insisted on Spring Security seamlessly meshing with our campus Shibboleth 2 Single Sign-On process. This is a bit like logging in without signing in – and not one of the core principles of Spring Security out of the box (generally concerned with classic Authentication via web form submission). It was therefore useful to see the information on Multiple Authentication in Chapter 11 (as I built a JPA example similar to Chapter 11 in this book).This book (as cookbook code format) immediately helped with understanding code syntax, formatting, location and common usage. Packt commonly uses headings like (Getting Ready, How to Do It, How It Works, There’s more and See Also) – but admittingly I was searching for code fragments that were similar to my needs – so it was the code (the How to Do It paragraphs) that I appreciated/needed the most.Also of note, many Maven related examples in the book and downloaded sample applications. Of note in the downloaded source (which may easily be the most valuable resource of this book, as the author produced an incredible amount of great code): * Useful examples of Maven POM dependency configurations * Nice to see hibernate configuration examples with classic persistence.xml settings (in contrast to Springs Pet Clinics XML based persistence layer API). * DAO objects, Glassfish JDBC configuration examples. * Nice interface and implementation services. * Example MVC controllers using Spring Security (very useful to see worked out examples). Again, largely XML based configuration versus annotation based. At the day job, we use a ton of annotation spring security objects as we needed a lot of overriding of core spring security API.Although some amount of examples utilize JDBC wired up with GlassFish (Chapter 7, 8, 9 and 11), and the commercial support for GlassFish has been halted by Oracle, the community version is still very active and working through these examples are largely unaffected by this issue.Chapter 1 of the Spring Security Cookbook dives into the topic of security with Java Authentication and Authorization Service (JAAS) - which I hadn't any experience with (typically using a framework of one type of another over the years to obtain these common services). The point I want to make here was this chapter didn't help me with the Spring Integration issues I has having – but did introduce me to some related and legacy core java services – and it was interesting reading. Having not known about these services to begin with, I admit I was a bit lost immediately and had me wondering what up, so to speak. Very interesting code in Chapter 11 examines implementing JAAS with Spring Security.Also, in review of many of the following chapters, (Spring Security with Struts, JSF, Grails, GWT, Vaadin, Wicket) I wanted to note that my development was classic JSP, Web 3.0 servlets and Spring MVC Core services through a standard Maven Eclipse project.Fortunately, the code fragments in the book of each of these frameworks required similar solutions to some of the problems I was having (and many were MVC based anyway) – and were useful. Even if the frameworks being discussed were not of particularly of interest to me (for my current job).Chapter 10 – Spring Security with Spring Web Services is a technology that I will be searching for solutions in about 2 months – as we begin to implement our ESB, as securing our Web services will be a hot topic for some time (very useful to see the cxf-servlet.xml example and generated Apache CXF WSDL here).To summarize, as there are a ton of issues I could write about (Java based configuration versus XML based configuration – both in the Spring MVC and Spring Security worlds for example), I wanted to close with an acknowledgment and recognition of the tremendous amount of work it took to build out all of the samples and code in Spring Security 3.x Cookbook – just wanted to say nice work!
Amazon Verified review Amazon
Florian Lopes Dec 12, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
First, I would like to thank Packt Publishing, for offering me this eBook.Here is my review about this book :It’s a great recipe of good practices, the reader can learn trough simple steps.It's a great way to learn spring security in combination with various frameworks, especially with spring social.I particulary appreciated the part where the author implements his own oauth access.Additionaly, you can download examples of code, given by the author, to complete your practice.At the end, it’s a great book to improve skills in security, and Spring Security developments.
Amazon Verified review Amazon
Michael J Waluk Feb 15, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book has an interesting approach to the cookbook theme - most recipes describe integrating the Spring Security framework with a specific web framework. If you're just starting out with Spring Security, or applying it to a new framework, this book will save you a lot of time - well worth the book's price. These include Struts 2, JSF, Grails, GWT, Vaadin, Wicket and web services (REST and SOAP).There are also recipes on using it with Hibernate, MongoDB, JAAS, Captcha, multiple authentication providers, LDAP and Spring Social (OAuth, Facebook, Twitter). It doesn't go into extending Spring to do things like locking users out or counting invalid authentication attempts, etc. but covers basic authentication and authorization in the various use cases. There's probably room for another cookbook on extension recipes.I found this very useful for the Spring Social recipes, but if you're securing a new project this could save you days of work.
Amazon Verified review Amazon
Amazon Customer Oct 17, 2014
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Yep, it's OK. I bought it mainly for the Grails info. Basic and a bit thin. It should have twice as much material and be twice as expensive.Really we need a book with a good solid grounding in Spring Security Core and UI for Grails. This isn't quite it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.