Sunday, October 14, 2012

Implement XA-Datasource in JBOSS


We have created a sample app which transfers money between two bank account databases. This task is fulfilled by an ejb method.
Lets called first bank as Akila and the other banks as Sithum. We need to create two different databases for two different banks. then we need two create two different data source as describe earlier. But in this case, we used XA-datasource. So lets start implement our sample application.

First we are going to create two datasources for two banks called akila-ds.xml and sithum-ds.xml. I am going to show only one -ds.xml file. But you have to do is, you can change jndi name only. 


<?xml version="1.0" encoding="UTF-8"?>
<datasources>
     <xa-datasource>
         <jndi-name>jdbc/akilads</jndi-name> 
         <xa-datasource-property name="URL">jdbc:mysql://localhost:3306/mazhar_db</xa-datasource-property>
         <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
         <user-name>root</user-name>
         <password></password>
         <track-connection-by-tx>true</track-connection-by-tx>
         <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
         <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
         <min-pool-size>1</min-pool-size>
         <max-pool-size>10</max-pool-size>
         <idle-timeout-minutes>10</idle-timeout-minutes>
         <metadata>
             <type-mapping>mySQL</type-mapping>
         </metadata>
     </xa-datasource>


Above file contains the data source for akila_db.  By editing jndi name and the URL we can create a data source file for the other bank. Main difference of this file with the previous datasource file is that this contains ‘xa-datasource’ instead of ‘local-tx-datasource’. We need ‘xa-datasource’ here because we have to handle a transaction between two databases. Don’t forget to begin the jndi name with ‘jdbc/’ .
In order to make a ‘mysql jdbc connection’ with ‘jboss’ we have to copy and paste ‘mysql-connector-java-5.1.13-bin.jar’ in jbossas/server/xxx/lib folder.

Now we need to do some coding in our application. So create a new enterprise application. Then go to ejb and write down following code.

Context initCnt = new InitialContext ();
DataSource ds = (DataSource) initCnt.lookup("java:jdbc/"+from+"bankds");

Then we have to create a database connection and make use of it.

ds.getConnection().createStatement().executeUpdate("Update user_amount set amount=amount-"+amount+ " WHERE user='"+user1+"'");

This ‘getConnection()’ method gets a connection from connection pool and releases it as configured. Connection pool is created by the ‘-ds.xml’ file definition.
In addition to this we have to handle some sql exceptions.
Not only the ejb but also the web.xml file should be modified to make database connections. Add this code inside the ‘<webapp>’ tag

<resource-ref>
<description>Oracle Datasource</description>
<res-ref-name>jdbc/mazhards</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<resource-ref>
<description>Oracle Datasource</description>
<res-ref-name>jdbc/zaheerds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

Finally following code should be added to the ‘jboss-web.xml file’

  <resource-ref>
  <res-ref-name>jdbc/akilads</res-ref-name>
<jndi-name>java:/mazhards</jndi-name>
</resource-ref>

<resource-ref>
<res-ref-name>jdbc/sithumds</res-ref-name>
<jndi-name>java:/zaheerds</jndi-name>
</resource-ref>

Now open up your browser and do the transaction.


=================================================

So I know that i can write up to 140 characters in this box.
 http://bit.ly/RgNp89
=================================================












Login module with database connectivity in JBOSS

We need to create a MySQL database to store usernames, passwords and rolls of users. So create a database called akila_db and create two tables called myuser and myuser_roles. Then add following data to database.

myuser table
username      password
akila               akila
sithum            sithum

myuser_roles table
username    role
akila              admin
sithum           guest

Then we have to edit login-config.xml in server/xxx/conf folder.


<application-policy name = "akila_policy">
       <authentication>
          <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule" flag = "required">
             <module-option name = "unauthenticatedIdentity">guest</module-option>
                                                 <module-option name = "dsJndiName">java:/ifsds</module-option>
             <module-option name = "principalsQuery">SELECT password FROM myuser WHERE username=?</module-option>
             <module-option name = "rolesQuery">SELECT role, 'Roles' FROM myuser_roles WHERE username=?</module-option>
          </login-module>
       </authentication>
    </application-policy>


Remaining things are similar to Basic authentication login module as we discussed earlier. So click here  find out about basic authentication login module.

Data source file in JBOSS

So far, we did not discuss about database connectivity. But in this article, we are going to discussed about database connectivity in JBOSS. In jboss we have three kind of data sources.

1.<local-tx-datasource>
     Identifies a data source that uses transactions, even distributed transactions
     within the local application server, but doesn't use distributed
    transactions among multiple application servers.

2.<no-tx-datasource>

   Identifies a data source that doesn't use transactions. This option
   isn't shown in the example, but would appear in place of the
  <local-tx-datasource> tag.

3.<xa-datasource>

  Identifies a data source that uses distributed transaction among multiple
  application servers. This option isn’t shown in the example, but
  would appear in place of the <local-tx-datasource> tag.

Let's see how we implement those data sources in our applications.


With java applications we can make database connections by adding ‘jdbc’ drivers.  There programmers have to spend a lot of time in database connection management. Every time a ‘getConnection ()’ method is called a new database connection is created and it may result in a connection bottleneck. ‘Jboss’ provides an efficient way for database connection management. It is called connection pooling.
A database is referenced from an enterprise application as a data source.  Depending on whether the database is accessed from web app or ejb configuration details differ.
First of all we should create a data source file to be used by the authentication method.  Name it as akila-ds.xml and save it in server/xxx/deploy folder.  Add the below content to it. (-ds.xml is mandatory here because the server identifies a data source file by that extension)


<?xml version="1.0" encoding="UTF-8"?>
<datasources>
       <local-tx-datasource>
     <jndi-name>akilads</jndi-name>
     <connection-url>jdbc: mysql://localhost:3306/ifs_db</connection-url>
     <driver-class>com.mysql.jdbc.Driver</driver-class>
     <user-name>root</user-name>
     <password></password>
<validconnectioncheckerclassname>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
     <min-pool-size>10</min-pool-size>
     <max-pool-size>100</max-pool-size>
     <metadata>
     <type-mapping>mySQL</type-mapping>
     </metadata>
     </local-tx-datasource>
 </datasources>


Jndi name component must contain the file name without ‘-’. (akila-ds.xml -> akilads)  

Here we are going to use MySQL database. Now we created the data source file. In next article, we will see how we use this file to achieve Basic authentication login module with stored data in a database. 


Enable buddy replication in JBOSS


To enable buddy replication you need to edit a configuration file in the nodes. Go to following directory and open the jboss-cache-manager-jboss-beans.xml file.

{JBOSS_HOME}\server\node3\deploy\cluster\jboss-cache-manager.sar\META-INF\jboss-cache-manager-jboss-beans.xml

Then you need to edit buddy replication mbean. Find the <property name="buddyReplicationConfig"> tag and set following tag to true in all the nodes within the cluster.

<property name="enabled">true</property>

Session Replication in JBOSS


We need to edit some configuration files to achieve session replication.
First go to the application web.xml file then add <distributable/> tag inside the <web-app> tag.
Then open the jboss-web.xml file and add following tag inside the <jboss-web> tag.


<replication-config>
        <replication-trigger>SET_AND_NON_PRIMITIVE_GET</replication-trigger>
        <replication-granularity>SESSION</replication-granularity>
        <replication-field-batch-mode>true</replication-field-batch-mode>
    </replication-config>

Then we need to edit some configuration files in the server. So we need to add jvmroute to server.xml file. Open the server.xml file located in {JBOSS_HOME}\server\node1\deploy\jbossweb.sar\server.xml. 
Find following tag.

<Engine name="jboss.web" defaultHost="localhost">

Then change it as follows.

<Engine name="jboss.web" defaultHost="localhost" jvmRoute="node1">

Then uncomment following tag in the server.xml file.

<Valve className="org.jboss.web.tomcat.service.sso.ClusteredSingleSignOn" />

Do these changes for all the nodes of the cluster. 
Now we completed session replication part also.. 
Cheers.. :)

Farming in JBOSS


We need not to copy the same ear file to all the nodes. There is a method call farming. So we can deploy to 
only one server and  automatically deploy to other nodes also. Go to a node and open farm folder inside “all” 
directory. Then paste into that folder. Then that project automatically deploy to other nodes. Remember, we 
we need to start all the servers to achieve this. Once start the servers, we can copy our ear file in to one 
"farm" folder inside one server. 

Cheerss..!!!


Testing cluster with three computers in JBOSS


First we have to create a cluster with three nodes. One node means one machine. That all three computers should be jboss installed. Then we need to start jboss with all configuration and bind with computer IP address. Therefore open the command prompt and go to the jboss bin directory. Then run following command.
Run.bat –c all –b 192.168.1.140 –Djboss.messaging.ServerPeerID=1
This serverPeerId should be unique within a cluster. Since we have three computers in our cluster, we need to start jboss with different peerIDs and corresponding IP’s by running above code.
Now we have created a cluster. Then we need to create a load balancer. So we need to install apache http server on one of above three machine or separate machine. We need not to install apache on every computers.
Go to the following link to download apache http server. Then download and install win32 MSI installer.  It is better not to install inside program files. Because the is a space between “Program file” directory. So in could be a problem. So create a new folder called apache inside C drive and install into that folder.


We are going to use mod_jk.so connecter for load balancing. We have to download mod_jk.so file from following link.


you need to download tomcat-connectors-1.2.37-windows-i386-httpd-2.2.x.zip. Because we used apache 2.2.22. 
Then unzip the downloaded file and copy that mod_jk.so file into modules folder inside apache installed directory.
Then go to the apache conf folder. Now create a file called mod_jk.conf and add following code to that file.

LoadModule jk_module modules/mod_jk.so
JkWorkersFile conf/workers.properties
JkShmFile logs/mod_jk.shm
JkLogFile logs/mod_jk.log
JkLogLevel info
JkMount /FarmTest-war/* loadbalancer

Most important part of above code is jkMount part. /FarmTest-war/* is the URL pattern of the clustered resource. So you need to specify your clustered resource here.
Then create another file called workers.properties inside the conf folder. This is the file that we specify cluster details. Add following code to that file.

# Define list of workers that will be used
     # for mapping requests
       worker.list=loadbalancer,status
     # Define Node1
     # modify the host as your host IP or DNS name.
       worker.node1.port=8009
    worker.node1.host=192.168.1.140
      worker.node1.type=ajp13
      worker.node1.lbfactor=1
       worker.node1.cachesize=10
     # Define Node2
     # modify the host as your host IP or DNS name.
       worker.node2.port=8009
       worker.node2.host= 192.168.1.141
       worker.node2.type=ajp13
       worker.node2.lbfactor=1
       worker.node2.cachesize=10
 #define node3
worker.node3.port=8009
       worker.node3.host=192.168.1.142
       worker.node3.type=ajp13
       worker.node3.lbfactor=1
      #worker.node1.local_worker=1 (1)
       worker.node3.cachesize=10
           
     # Load-balancing behavior
       worker.loadbalancer.type=lb
       worker.loadbalancer.balance_workers=node1,node2,node3
       worker.loadbalancer.sticky_session=1

Then open the httpd.conf file which located inside the conf folder. Then add following line of code to the bottom of that file.

Include conf/mod_jk.conf

Now restart the apache server.
Then start all jboss nodes.
We have created a load balancer and cluster with three nodes. Now we need to deploy an application to the cluster.  Create a small enterprise application and deploy it with one machine. Then go to the deploy folder inside the “all” folder. Now copy the application “war” file and paste it to the farm folder inside the “all” folder.
Now we deployed an application to the cluster. Now open a web browser and go to following link.
This IP address is the IP address of apache installed computer. 



Understanding Load balancing


Imagine you have a retail web application running on a single application server
instance and that you average 10,000 customers a month. Your company decides to
run a TV advertisement and predicts that you may start getting 100,000 customers a
month. You’re tasked with making sure that the application can support this number
of users. In addition, your application needs to be highly available. To accomplish
these goals, you have to deploy multiple application server instances and balance
requests across them.
Load balancing is a way of balancing incoming load, or concurrent requests, across
multiple application server instances, making your applications scalable and highly
available. Scalability is a term used to describe the ability to make your application
handle more user load by adding hardware and/or creating redundant instances of
your application without having to change code. Load balancing can help scale your
application because you can add more servers for the load balancer to balance the
load across, increasing the amount of traffic your application can handle. High availability
is the ability to continue processing requests in the face of server failure.

The load balancer acts as a single point of entry into an application environment
as well as a traffic director for requests.




TYPES OF LOAD BALANCERS
Load balancing can be done in two primary ways: with a hardware load balancer or
with a software load balancer. Hardware load balancers are typically more expensive
but are also more reliable


Load balancers typically make a single IP address for a cluster visible to clients. The
load balancer maintains a map of internal (or virtual) IP addresses for each machine
in the cluster. When the load balancer receives a request, it rewrites the header to
point to a particular machine in the cluster. If a machine in the cluster is removed or fails, the
hardware load balancer has the ability to recognize the failure and avoid
routing requests to it.



Understanding JBOSS Clustering


Clustering is the act of running the same application on multiple application server
instances simultaneously with each application server being aware of the others in the
cluster. An application server that’s part of a cluster is known as a node. But just having
nodes aware of other nodes in a cluster isn’t interesting. The nodes in the cluster must
be able to communicate with each other to do something useful, such as replicating
state or providing failover capabilities. Before we dive into the specifics of the clustering
features that JBoss offers, let’s examine some of the fundamental concepts behind
clustering. And, because you can’t seem to talk about clustering without talking about
load balancing, let’s start with that.

Introduction to jboss clustering and load balancing


A single JBoss server can handle several hundred concurrent requests; but, if your
application has to scale to support multiple thousands of concurrent requests or
multiple millions of requests a day, then a single application server probably won’t
do the trick. JBoss enables you to simultaneously run your application on multiple
application servers. Requests going to your application can then be balanced across
these servers, and your application can also withstand individual server failures.
This deployment architecture allows you to achieve maximum scalability with minimal
downtime. Clients need not know that their different requests may be handled
by different servers.
Java EE doesn’t specify any standards for how clustering services should work.
Every application server implements clustering differently and provides a different
set of clustering capabilities and services. Red Hat has set out to make cluster setup a simple task. As you’ll learn in this chapter, clusters are easy to create in JBoss and
require minimal configuration. Adding nodes requires no administrative management
because nodes detect each other automatically over network protocols. JBoss
also provides a sophisticated distributed cache that allows stateful components to replicate
their states across multiple nodes in a cluster, enabling you to easily develop
fault-tolerant applications, with very little code.


Client cert authentication mechanism in JBOSS


This authentication mechanism is almost same as mutual authentication. But there are some differences between those two authentication mechanisms. In client cert authentication, we don’t have to enter usernames and passwords. Web browser keeps server certificates and verifies with certificate that the server sends at the beginning of a conversation.
Let’s see how to implement client cert authentication.
We have to edit some configuration files to achieve client cert authentication.
First we have to change the web.xml in the application. Add following authentication method within login-config tag. Other tags are remaining same as the mutual authentication.


<login-config>
        <auth-method>CLIENT-CERT</auth-method>
        <realm-name>JBoss JMX Console</realm-name>
    </login-config>


Go to following directory and open the server.xml file.

C:\jboss\jboss-eap-5.1\jboss-as\server\default\deploy\jbossweb.sar

Then find following tag and edit it as follows.

<Realm className="org.jboss.web.tomcat.security.JBossWebRealm"
            certificatePrincipal="org.jboss.security.auth.certs.SubjectCNMapping"
            allRolesMode="authOnly"/>       

Then create a security domain in login-config.xml as follows.


<application-policy name="simple-security-domain">
<authentication>
        <login-module code="org.jboss.security.auth.spi.BaseCertLoginModule"
                      flag="required">
            <module-option name="password-stacking">useFirstPass</module-option>
            <module-option name="securityDomain">java:/jaas/simple-security-domain</module-option>
        </login-module>
        <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
                      flag="required">
            <module-option name="password-stacking">useFirstPass</module-option>
            <module-option name="usersProperties">props/cert-user.properties</module-option>
            <module-option name="rolesProperties">props/cert-role.properties</module-option>
        </login-module>
    </authentication>
</application-policy>


We need to create two new properties files inside the props directory called cert-user.properties as cert-role.proerties. but the names can be any names whatever you like. In this case, cert-user.properties file should be empty.  Then open the cert-role.properties file and following things to that file.

Username=admin
Username2=guest

This username has some special things. This username should be same as the client certificate’s common name and the alias of client certificate that saved in server.trustore.
Then go to jboss-web.xml file in the application add security domain as discussed in early login module topics.
After that we have to add mbean into jboss server. This mbean is a service. So we have to add new xml file into following directory. File name of that xml should be somename-service.xml. In my case, the file name is jboss-service.xml.

C:\jboss\jboss-eap-5.1\jboss-as\server\default\deploy

Then add following code into the jboss-service.xml file.


<mbean code="org.jboss.security.plugins.JaasSecurityDomain"
       name="jboss.ch8:service=SecurityDomain">
    <constructor>
        <arg type="java.lang.String" value="simple-security-domain"/>
    </constructor>
    <attribute name="KeyStoreURL">${jboss.server.home.dir}/conf/server.truststore</attribute>
    <attribute name="KeyStorePass">password</attribute>
</mbean>


This password is the password for server.trustore.
We have described about client.pfx files in mutual authentication section. As described in that section, we have to import client.pfx file into the browser.
Now we are done with the client-cert login.

Mutual authentication in JBOSS


Run the commands below in the command prompt within default\conf directory. Copy keytool.exe, all the files in openssl/bin folder. 

Create a self signed client certificate
1).Create private key:

 openssl genrsa -des3 -out client.key 1024

2).Create a csr:

openssl req -new -key client.key -out client.csr –config openssl.cnf

3).Create the client certificate:

openssl x509 -req -days 365 -in client.csr -signkey client.key -out client.crt

            4). Convert client.key to client.pem 

openssl rsa -in client.key -out client.pem 

          5). Convert the certificate to .pfx

openssl pkcs12 -inkey client.pem -in client.crt -export -out    client.pfx

Go to internet explorer and import client.pfx. You will have to provide the password which you introduced when creating the pfx.  You can see it under personal certificates. Then you can save the client.crt inside server.keystore in default/conf. 


Security certificates and authentication in JBOSS


Before moving onto the client-cert authentication let’s have a basic idea about public key certificates.
In the previous authentication methods we could only encrypt authentication details at the best case.
That is insecure because an eavesdropper can read our content easily if they have the tools. So the content should also be encrypted as well. Server first sends its public key to the browser and browser encrypts the content with that key and the server decrypts. Problem with this protocol is that we don’t have the data source integrity.  Certification authorities are there to certify the identity of web servers.  Browser can verify that certificate with the available certificates.

The above mentioned authentication mechanism is called server only authentication because only the identity of the server is specified. Note that this authentication is done at the protocol level.

 First you have to find keytool.exe located at “C:\Java\jdk1.6.0_32\bin” and copy it to “C:\jboss-eap-5.1\jboss-as\server\default\conf”.

Change your command line working directory to the above and execute

     keytool -genkey -alias serverCert -keyalg RSA -validity 1500 –keystore server.keystore

This command creates a server certificate which is valid for 1500 days and stores it in server.keystore.
When you execute this you will be asked to fill some details and add a password to the key store.
 Locate server.xml at “C:\jboss-eap-5.1\jboss-as\server\default\deploy\jbossweb.sar” and include 

<Connector port="8443"
scheme="https"
secure="true"
clientAuth="false"
keystoreFile="${jboss.server.home.dir}/conf/server.keystore"
keystorePass="serverpass"
sslProtocol = "TLS" />

Under an existing connector element.  For the keystoreFile attribute you must provide the name of the key store you created before, to store server certificates and keystorepass should be key store’s password.
 Add a transport guarantee in the web.xml’s security constraint element.

<user-data-constraint>
  <description>Require SSL</description>
  <transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>

This guarantees that even we connect to an insecure port we are redirected to a secure port as specified in server.xml. You can either specify an auth-method in the web.xml or not. Now you can open the URL in your browser and see the http request is redirected to a port which handles https.
In addition to the server you can also authenticate the client. We have two type of mechanisms.. Those mechanisms will discussing in future articles.




Digest Authentication in JBOSS


This authentication mechanism is almost same as the basic authentication. But the different is, in basic authentication, we store password as plaintext. In digest, we store password after encrypted using encryption algorithm such as MD5. Let’s see how to create digest authentication login module.
First we have to change web.xml file. We have to add following code instead of basic authentication code.


<login-config>                                                                                                                                          
  <auth-method>DIGEST</auth-method>                                                                                                                    
  <realm-name> My Secure Content Authentication </realm-name>                                                                                                          
</login-config>


Then we should create new application policy for digest authentication. So we have to edit           login-config.xml file. So add following application-policy to the login-config.xml file.


<application-policy name="MyApp">
 <authentication>
 <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
 <module-option name="usersProperties">props/digest-users.properties</module-option>
 <module-option name="rolesProperties">props/digest-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>
 </login-module>
 </authentication>
</application-policy>


According to the application policy name, edit the security domain in jboss-web.xml. In my case, security domain in MyApp.
Then we should encrypt the password. Because we need to store encrypted password. Then type following command. Then you will get encrypted password.

java –cp C:\jboss\jboss-eap-5.1\jboss-as\common\lib\jbosssx-server.jar / org.jboss.security.auth.spi.RFC2617Digest username "Realm name" password

Username= we have to give username
Password=Real password
Realm name= the realm name that we specify in web.xml.

Finally you have to store the hashed password as opposed to the plaintext password, in the users.properties file specified in the application policy. roles.properties file   remains same as that of basic authentication implemented with UserRolesLoginModule. 

Form Based authentication in JBOSS


We discussed about basic authentication in JBOSS. Now we are going to discuss about form based authentication. As we discussed earlier, we have four types of authentication mechanisms.

As the name suggests, credentials are taken from a user filled form.  In addition to the changes done above we have to add a login config element to the web.xml outside the security constraint element and inside web-app element. It should be noted that only one login config block should be there.

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


We have to create different jsp files, login.jsp, loginfail.jsp and logout.jsp.  We should add a login form in the body of login.jsp.

<form method="post" action="j_security_check">
            <input type="text" name="j_username" /><br/>
            <input type="password" name="j_password" /><br/>
            <input type="submit" value="Login" />
</form>

If the login is failed code in the loginfail.jsp will get executed.

<%
String redirectURL = "/Form-Base-Auth-war/FormServlet";
    response.sendRedirect(redirectURL);   
%>  

This code is written between jsp tags. In case of failure user is redirected to the login page.  
In the servlet we have given a link to logout.jsp.

out.println("<br/><a href='logout.jsp'>logout</a>");

Following is the body of logout.jsp.

<body>
        <%
     session.invalidate();       
%>
        <h1>Log Out successfully</h1>
       
      
      
        <a href="/Form-Base-Auth-war/FormServlet">home</a>
    </body>

Other things are reamain unchanged as Basic authentication. We have to add security domain to the jboss-web.xml, need to create two properties files, need to add security constrains as basic authentication. If you miss it you can see Basic authentication in JBOSS.

Session is successfully invalidated in form-based authentication unlike basic authentication. This works in any browser.




Basic authentication mechanism in JBOSS


Name implies that this is the basic authentication mechanism type in JBOSS. When we trying to access to secured resource, then application will ask about username and password. If username and password are correct, then user can access to the resource. Lets see how to enable basic authentication for a resource.

First create an enterprise application like earlier discussed. Then we have to do some configurations. So first open the web.xml file under configuration files of testApp-war. Then add following code within <web-app> tag.


<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Pages</web-resource-name>
<url-pattern>/protected_resource/*</url-pattern>
<http-method>POST</http-method>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description>Only allow users from following roles</description>
<role-name>guest</role-name>
   <role-name>admin</role-name>
</auth-constraint>
   
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>My Secure Content Authentication</realm-name>
 </login-config>


In the URL pattern tag you have to specify the URL of the secured webpage. You can specify more than
one URL pattern. A URL pattern beginning with ‘/’ and ending with ‘/*’ specifies a path mapping and ‘*.’
Specifies an extension mapping. String containing only ‘/’ specifies default server while all other strings
denote the exact matches.
<role-name> is the allowed rolls for secured resource.
Then we have to edit jboss-web.xml file also. That config file also locate in the previous directory. Open the jboss-web.xml file and add following code inside <jboss-web> tag.

<security-domain>java:/jaas/test_policy</security-domain>

Now we need to create a security domain in login-config.xml file which located under following directory.

{JBOSS_HOME}\server\default\conf\login-config.xml

Then add following application policy into login-config.xml

<application-policy name = "testPolicy">
       <authentication>
          <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
             flag = "required">
           <module-option name="usersProperties">props/testuser.properties</module-option>
           <module-option name="rolesProperties">props/testrole.properties</module-option>
          </login-module>
       </authentication>
    </application-policy>


Now we need to create two more properties file to achieve Basic authentication. Therefore go to following directory and create to properties files called testuser.properties and testrole.properties.

{JBOSS_HOME}\server\default\conf\props

then add following username names and passwords to testuser.properties file.

akila=akila
sithum=sithum

akila is the username and the password is akila.

Then add following username with the role inside the testrole.properties file.

akila=admin
sithum=guest

akila is the username and admin is the role of akila.

now we need to test basic authentication. So go to web browser and request to protected resource. Now you will see a pop-up box that asking about user name and password like below. Then enter your username and password. Now you can access your protected resource. 


:)