Skip to content
June 27, 2012 / techannotation

Glassfish – Basic authentication

A good and simple way to apply an authentication system to our web application is to use a basic role authentication.

This could be quickly configurated inside an application server and every web app gets the protection. In this article I’ll describe the use of it inside glassfish using a servlet which return the orders only for authenticated users.

Let’s see how it works.

The Common Annotations for the JavaTM Platform (JSR 250) defines an annotation set used for configuring security permissions inside Java code. 

It sounds good, doesn’t it? That is possible through annotation used for either type and method definitions. You can find a good list of annotation at http://java.sun.com/developer/technicalArticles/J2EE/security_annotation/.

Take a note about at the half of the page: “The @PermitAll, @RolesAllowed, @DenyAll annotations are not supported in servlets. When using servlets, specify authentication and authorization in the web.xml deployment descriptor“.

Let’s start with some code. First, the servlet.

package it.sample.ordersecurity;

import it.sample.ordersecurity.bean.Order;
import it.sample.ordersecurity.bean.OrderList;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 * Servlet implementation class Report
 */
@WebServlet("/Report")
@ServletSecurity(@HttpConstraint(rolesAllowed = "guest"))
public class Report extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Report() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
     OrderList orders = new OrderList(
       new ArrayList<Order>(){{
        add(new Order("CF-0122", 11.5, 23));
        add(new Order("AK-2766", 2.21, 50));
        add(new Order("CR-2400", 222, 1221));
       }}
       );
     
     PrintWriter writer = response.getWriter();
     
  try {
   JAXBContext contextObj = JAXBContext.newInstance(OrderList.class);

   Marshaller marshallerObj;

   marshallerObj = contextObj.createMarshaller();
  
   marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  
         marshallerObj.marshal(orders, writer);
         
  } catch (JAXBException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally
  {
   writer.close();
  }             
 }
}

The url /Report gets the order’s list in xml format. This list could be seen only by “clerk” role. Let’s to configurate it inside glassfish,

 In this picture you can see how to add a role users inside glassfish administration console.

 I dont’ want to go into the deep of this argument, you can find out a lot of information about it at official glassfish guide.

Once We’ve done this step, we can configurate a web.xml file:


<?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_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>OrderSecurity</display-name>
	<security-constraint>
		<web-resource-collection>
			<web-resource-name>SecureResource</web-resource-name>
			<url-pattern>/*</url-pattern>
			<http-method>GET</http-method>
			<http-method>POST</http-method>
		</web-resource-collection>
		<auth-constraint>
			<role-name>clerk</role-name>
		</auth-constraint>
		<user-data-constraint>
			<transport-guarantee>NONE</transport-guarantee>
		</user-data-constraint>
	</security-constraint>

	<login-config>
		<auth-method>BASIC</auth-method>
		<realm-name>file</realm-name>
	</login-config>
</web-app>

We’ve configured a login basic authentication for all the paths in get and post method.

Now we have to mapping the role-name with the group-name.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
<sun-web-app>

	<security-role-mapping>
		<role-name>clerk</role-name>
		<group-name>clerk</group-name>
	</security-role-mapping>
</sun-web-app>

Browsing the url http://localhost:8080/OrderSecurity/Report you must authenticate with the user “clerk”:

And the result is the follow:


<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<orders>
  <order>
    <invoice>11.5</invoice>
    <itemNumber>23</itemNumber>
    <orderId>CF-0122</orderId>
  </order>
  <order>
    <invoice>2.21</invoice>
    <itemNumber>50</itemNumber>
    <orderId>AK-2766</orderId>
  </order>
  <order>
    <invoice>222.0</invoice>
    <itemNumber>1221</itemNumber>
    <orderId>CR-2400</orderId>
  </order>
</orders>

Summary

We’ve seen a very easy way for protecting document and authenticate the user. As you can see, you don’t have to edit and change your business logic into your code if you want apply that. It’s enough adding some annotation into your class and into configuration files.

About these ads

3 Comments

Leave a Comment
  1. techannotation / Jul 13 2012 8:26 am

    Thanks to Glassfish team to have published this post in their daily posts summary
    (https://blogs.oracle.com/theaquarium/entry/tab_sweep_primefaces3_datasourcedefinition_jpa)

  2. Anonymous / Jan 9 2013 9:32 am

    what is here order and orderlist?

    • techannotation / Jan 9 2013 9:49 am

      Yes, I’m sorry. You can find them at “5 minutes with – Spring REST” articles from this blogs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: