Wednesday, October 18, 2006

JBOSS LDAP Integration

By Sandrick Melbouci

This article provide a prototype of integration of J2EE applications such as Servlets/JSPs, EJBs, MDBs with LDAP (Lightweight Directory Access Protocol) for application authorization and authentication. This article identifies some key interfaces within JBoss and any J2EE container compliant application server that can be configured to provide a secured access. We will provide a declarative LDAP security model in such a way you can configure it at runtime.

Few things to take in consideration:
- J2EE uses the same authorization model for both web-based components (servlets and JSPs) and enterprise components (EJBs). The specification requires transparent propagation of security credentials within the J2EE environment, so that once a user has authenticated to any J2EE component, the same security information is used by all other components.
- J2EE application programming model insulates developers from mechanism-specific implementation details of application security. J2EE provides this insulation in a way that enhances the portability of applications, allowing them to be deployed in diverse security environments.
- In order to integrate authorization into an unknown authentication mechanism, J2EE specifications define a simple role-based security model for EJBs and Web components. the specification defines a number of terms about security:
- A realm is the J2EE term for the security policy domain that is a definition of the way in which a user is authenticated. In its simplest form, a realm is a list of users and a mechanism for authenticating those users. Basic HTTP authentication is known as the HTTP realm; a public key certificate (PKC) authentication such as SSL is a different realm.
- A principal is the name of a user within the authentication realm. Although the J2EE specification does not require the principal name to be the same as the user's login name, most (if not all) J2EE implementations use the username as the principal name.
- A role is a definition of the way a user will use the system. Typical roles will be user, administrator, manager, developer, researcher, and so on. Outside the J2EE domain, a role is usually implemented by assigning users to one or more authentication groups or granting privileges to user accounts.
- A role reference is the name of a role used within the code of a J2EE application. As part of the J2EE application environment definition (known as the deployment descriptor), every role reference must be mapped onto a real role. The decoupling of the coded role reference from the actual role helps improve portability of a J2EE component.

Before we define the LDAP schema (LDIF file), the following are the LDAP common terms you need to know in order to understand this configuration.
To configure LDAP, refer to LDAP Admin guide

DN: Distinguished Name
A distinguished name uniquely identifies an entry in the directory. A DN is made up of “relative” distinguished names of the entry and each of the entry's parent entries, up to the root of the directory tree. These names are usually separated by commas and optional spaces. For example: 'uid=JohnDoe, ou=People, dc=company, dc=com'.
ObjectClass
An objectclass is a formal definition of a specific kind of objects that can be stored in the directory. An objectclass is a distinct, named set of attributes that represents something concrete, such as a user, a computer, or an application.
LDAP URL
LDAP URL is a string that specifies the location of an LDAP resource. An LDAP URL consists of server host and port, search scope, baseDN, filter, attributes and extensions.
Schema
An LDAP schema defines a set or rules that specifies the types of objects that a directory may contain and the required and optional attributes that entries of different types should have.

More details can be found in LDAP Admin guide.

Now, Let's define our LDAP schema to support the J2EE role-based security. Below is the LDAP structure that defines our LDAP tree:

com
---company
------------People
-------------------admin
-------------------demo
------------Roles
------------------Administrator
------------------Users


This structure is orgonized into 2 main structures, People and Roles. People contain the users and Roles groups the users into group of roles. A role is defined above, it provides the permission level for a user.

The following is the LDIF schema that also defines our LDAP entries.


dn: dc=company,dc=com
dc: company
objectClass: top
objectClass: dcObject
objectClass: domain

dn: ou=Roles,dc=company,dc=com
ou: Roles
objectClass: top
objectClass: organizationalUnit

dn: ou=People,dc=company,dc=com
ou: People
objectClass: top
objectClass: organizationalUnit

dn: uid=demo,ou=People,dc=conpany,dc=com
uid: demo
objectclass: person
objectclass: inetOrgPerson
cn: demo
sn: demo

dn: uid=admin,ou=People,dc=company,dc=com
uid: admin
objectClass: person
objectClass: inetOrgPerson
cn: Admin
sn: admin

dn: cn=Administrator,ou=Roles,dc=company,dc=com
cn: Admin
objectClass: top
objectClass: groupOfNames
member: uid=admin,ou=People,dc=company,dc=com

dn: cn=Users,ou=Roles,dc=company,dc=com
cn:Users
objectClass: top
objectClass: groupOfNames
member: uid=demo,ou=People,dc=company,dc=com
member: uid=admin,ou=People,dc=company,dc=com


Save this schema into a file called entries.ldif

You can load this file by running the command :
ldapadd -f entries.ldif -x -D "cn=Manager,dc=company,dc=com" -w secret

Manager is administrator of the LDAP

Check that your entries are loaded by executing the following command:
ldapsearch -x -b 'dc=company,dc=com' '(objectclass=*)'

We are done with LDAP.

This example has been tested with OpenLDAP. It should work with any other LDAP provider.

Now, we need to tell JBoss how to authorize and authenticate against the LDAP entries we have created.
For our example, we will secure the JBoss jmx-console. Similar thing can be applied to any web application.

We need to modify web.xml and add the security constraint.

web.xml

<security-constraint>
<web-resource-collection>
<web-resource-name>HtmlAdaptor</web-resource-name>
<description>An example security config that only allows users with the
role Admin to access the HTML JMX console web application
</description>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>Administrator</role-name>
</auth-constraint>
</security-constraint>


<security-role>
Administrator
</security-role>


As you can see, we wanted only the users having a role "admin"to access the console.


Now we will tell JBoss what security scheme to use. To do so, we need to add security-domain element into jboss-web.xml. We have called our security scheme "AuthPolicy".

jboss-web.xml
<jboss-web>
<security-domain>java:/jaas/AuthPolicy</security-domain>
</jboss-web>


The "AuthPolicy" security policy shall be defined in login-config.xml located in :
$JBOSS_HOME/server/{config}/conf .
{config} can be one minimal, all, default or you can define your own.


Now let's define an entry in the login-config.xml. Remember, we will to define the LDAP URL defined above.

login-config.xml

<application-policy name="AuthPolicy">
<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="baseCtxDN">ou=People,dc=company,dc=com</module-option>
<module-option name="baseFilter">(uid={0})</module-option>
<module-option name="roleFilter">(member={1})</module-option>
<module-option name="rolesCtxDN">ou=Roles,dc=company,dc=com</module-option>
<module-option name="roleAttributeID">cn</module-option>
<module-option name="roleAttributeIsDN">false</module-option>
</login-module>
</authentication>
</application-policy>


I highlighted some attribute in red. These attribute should be mapped to your LDAP schema definition.

See it in action. Fire up JBoss, and then go to: http://localhost:8080/jmx-console.

References:
Security Trail in the Java tutorial, http://java.sun.com/docs/books/tutorial/security/index.html
Core Security Patterns, http://www.informit.com/bookstore/product.asp?isbn=0131463071&rl=1
JBoss Security Model, http://www.huihoo.com/jboss/online_manual/3.0/ch13s78.html
JBoss Login Module, http://wiki.jboss.org/wiki/Wiki.jsp?page=LdapLoginModule

Saturday, October 07, 2006

JAXB and xmlBeans. Pros ad cons

By Sandrick Melbouci

I would like to address some differences between JAXB and xmlBeans in processing of XML documents.
JAXB is a part of JavaEE standards and provides a convenient way to bind an XML schema to a set of Java classes. This allowsh an easy way to process data in java technology without having to understand all the ins and outs of te XML technology.
JAXB 2.0, available in in the open-source Java EE 5-compliant application server at Glassfish project is part of the new integrated stack for Web services development. This new version of JAXB includes all the data binding functionality in a single package, while the previous Web services development stack (in Java Web Services Developer Pack 1.6 and previous versions) carried out some data binding in the JAX-RPC 1.x package and some in the JAXB 1.x package. With the integrated stack comprising JAX-WS 2.0, JAXB 2.0, and SAAJ 1.3, the Web services description, data binding, and SOAP attachment processing functionality are more logically architected, enabling you to develop Web services, middle tier and Web applications more easily.

XmlBeans was originally developed by BEA Systems, it is now an open source project. xmlBeans provide similar functionality then JAXB but may require some good knowledge of XML technology.
Prior to this technologies, one way to proccess an XML document, perhaps the most typical way, is through parsers Simple API for XML (SAX) or the Document Object Model (DOM). Both of these parsers are provided by
Java API for XML Processing (JAXP). The developer writes code to invoke a SAX or DOM parser through the JAXP API to parse an XML document -- that is, scan the document and logically break it up into discrete pieces. The parsed content is then made available to the application. In the SAX approach, the parser starts at the beginning of the document and passes each piece of the document to the application in the sequence it finds it. Nothing is saved in memory. The application can take action on the data as it gets it from the parser, but it can't do any in-memory manipulation of the data. For example, it can't update the data in memory and return the updated data to the XML file.
In the DOM approach, the parser creates a tree of objects that represents the content and organization of data in the document. In this case, the tree exists in memory. The application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.

Now we have 2 technologies that do convert the XML document into java classes. You manipulate the Java object instead. However, JAXB and XmlBeans accomplish the marshalling and unmarshalling of XML document quite differently.

XMLBeans processes an XML document without going through a conversion into Java where integrity of the document can be lost. XMLBeans creates a cursor that can move through the XML document. You can access any element of the document, including comments and schema information because the document is kept in full fidelity. It also creates the opportunity to execute an XQuery on the document. XMLBeans also gives a strongly typed access to the document and a more generic type of access, similar to a reflection API. However, it doesn't always work the way you want it. Many time an error like "Invalid XML character 0x0" by processing the same document where the processing was previously successful.
More importantly, like I previously mentioned it, Using Xml Beans requires you to know XML very well and also SAX and DOM.

JAXB is binded to the XML schema, the first release of JAXB did not answer the development community, mainly because it did not support all XML schema features and only supported DTDs. The first JAXB version suffered mainly of 3 major issues: it prevented support of type substitution and related features, it prevented support for extensibility and versioning, it failed to provide readable bindings in many cases.
JAXB 2.0 was enhanced to fill up the gaps and provides full XML schema support, Java to XML Schema mapping, schema evolution and portability. For ease of development, JAXB has leveraged J2SE 5.0 features: generics for type safe collections enum type for binding of simple type with enumeration facets better support for XML schema types using datatypes in JAXP 1.3 leveraging JAXP 1.3 validation for smaller footprint more compact binding based on constraining facets defined in schema.
JAXB architecture was re-designed to assist with schema evolution and invalid XML content. JAXB has introduced a flexible unmarshalling mode that allows for unmarshalling of invalid XML content. Optional unmarshal time validation can be used by an application to detect invalid XML content and decide whether to terminate unmarshalling.

Let's take an example to illustrate the basic usage of both technologies:

Let say we have a schema:

<xs:complextype name="promotion">
<xs:sequence>
<xs:element name="discount" type="xs:string">
<xs:element name="None" type="xs:string">
</xs:sequence>
</xs:complextype>



With XmlBeans:
PromotionDocument pdoc =
PromotionDocument.Factory.parse(new File (xmlFile));

// Get and print pieces of the XML instance.
Promotion p = pdoc.getPromotion;
with JAXB:
JAXBContext jc = JAXBContext.newInstance("test.jaxb");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Promotion p = (Promotion) unmarshaller(new File(xmlFile) );


The choice between these technology depends on the performance you want to get
and the use of XML features. I will go with XML Beans if:
I would like to access the XML document itself and use XQueries ...etc.
I would like Native DOM representation at the expense of performance and memory management.
Access schema metadata
Use it older JDK versions. 1.4 or older.


If you are looking for simplicity to convert an XML document <--> Java classes,
JAXB is your choice.
If you want binding customization, JAXB allows these declarations to be made "inline" -- that is, in the schema, or in a separate document.
JAXB uses memory efficiently: The tree of content objects produced through JAXB tends
can be more efficient in terms of memory use than DOM-based trees.
JAXB allows you to access XML data without having to unmarshal it. Once a schema is bound you can use the ObjectFactory methods to create the objects and then use set methods in the generated objects to create content.

References:
JAXB Architecture, http://java.sun.com/webservices/jaxb
JSR 31, JAXB specs, http://jcp.org/en/jsr/detail?id=031
XMLBeans, http://xmlbeans.apache.org/
XMLBeans Architecture, http://dev2dev.bea.com/xml/xmlbeans.html