Saturday, June 15, 2013

What is SAML (Security Assertion Markup Language) 2.0 ?

Security Assertion Markup Language 2.0 (SAML 2.0) is a version of the SAML OASIS standard for exchanging authentication and authorization data between security domains. SAML 2.0 is an XML-based protocol that uses security tokens containing assertions to pass information about a principal (usually an end user) between an identity provider and a web service. SAML 2.0 enables web-based authentication and authorization scenarios including single sign-on (SSO).

Friday, May 17, 2013

Create Vaadin project with maven

-->
today i am going to show you how to create a Vaadin project using maven. I am going to create a project that uses Vaadin 7.0.5. My development environment is as follows.

  • Ubuntu OS
  • JDK 7
  • maven 3
  • Intelli J IDEA 12
  • Apache tomcat 7

I am using ubuntu terminal throughout the development.

mvn archetype:generate \
   -DarchetypeGroupId=com.vaadin \
   -DarchetypeArtifactId=vaadin-archetype-application \
   -DarchetypeVersion=7.0.5 \
   -Dpackaging=war

then fill the required details as follows.


groupId - org.fosshub.vaadin
artifactId - vaadin-web-app
version - 1.0
package - org.fosshub.vaadin.sample

after creating the project, you can open the project with your preferred IDE. I am using IntelliJIDEA.
The opened project structure will be as follows.

now you can start coding with your created vaadin project.

Regards
Chathuranga Tennakoon

Friday, May 3, 2013

Spring Security - form based login + user details in XML + url based access control

this will be the first article that i am writing about the practical implementation of the Spring Security. throughout this article i am expecting to how the Spring Security framework is practically integrated with your Spring MVC Web Application. 

 Those who are new to Spring MVC can refer Spring MVC Web Application article before proceeding with this article. others can download the below source code to continue with this article.


expectation of this article is to discuss the following areas.

1. Form based user authentication with XML based userDetailsService
    (this userDetailsService is known as the In-Memory user detail service)

2. URL based access control with Spring Security


first open the project with your IDE.In my case, i am using Intelli J IDEA.  then you will see the overall project file and directory structure as follows.



then we can proceed with Spring Security Integration for this web application.

first we will look at why spring security is such important. as you are aware, each application can have several user levels. each user level is attached with set of  specific privileges known as user permissions. we should be able to restrict/grant the access for the different areas of the application based on the user level permissions. in order to archive that purpose, we will be using spring security framework. simply, Spring security will be used to control the user access (Access Control) of the application.


the application has not been integrated with the spring security framework yet. therefore you will find following security vulnerabilities of this application.

  1. non-authenticated users(guests) can access the home page dedicated for the authenticated users.    
        http://localhost:8080/spring-mvc-sample/user/home

  1. non-authenticated users(guests) can access the home page dedicated for the admin users.
         http://localhost:8080/spring-mvc-sample/user/admin/welcome


Now we are going to integrate the Spring Security framework with this web application to fix those security vulnerabilities. you can refer the following step to to integrate spring security with sample Spring MVC application given above.


  • first add the Spring Security maven dependency for the pom.xml file.
  •  then do the following spring security filter mapping in the web.xml file
    
  • then add a spring configuration xml file called spring-security.xml directly under the WEB-INF directory of the web application.  your spring-security.xml file should contains following security configurations and declarations.
      

  • finally location of the spring-security.xml file should be passed to the Spring Framework's ContextLoaderListener as contextConfiguration parameter. that can be done by modifying the contextConfigurationLocation parameter of the web.ml as follows.


Now you have successfully integrated your web application with Spring Security Framework.


now you can use following login credentials to check whether the above identified security vulnerabilities still exist.

User Credentials (who has ROLE_USER)

username : chathuranga
password : admin

Admin User Credentials (who has ROLE_ADMIN and ROLE_USER)

username : darshana
password : admin

completed source code of this post can be found at GitHub


i think this post might help you to get some understading of spring security.

Thanks and Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com
http://lk.linkedin.com/in/chathurangatennakoon


Thursday, April 18, 2013

Class variable Vs Instance variable in java


-->
both variables are defined inside the class and outside to any method. Therefore both of these variables are in the class scope.

Instance variable
instance variable belongs to an instance of a class. Each instance of the class maintain its own copy of the instance variable(s). Therefore the changes or operations that are done with an instance variable will only be reflected in that instance variable. (no other instance variables are affected)

here is an example for the instance variable.

class sampleClass{

    int count;
}


Class variable
class variables are known as static member variables. Class variable is common to the all instances of the class. In other words, one class variable will be shared with all instances of the class. Class variables are modified with static modifier.

Here is an example for the class variable.

Class sampleClass{
   
    static int count;
}

instance variable and class variable.
Each object(instance) in the class has its own copy of instance variables. But every instances(objects) in the class will be shared one copy of class variables. Therefore the changes that are done for the instance variables will only be visible to that particular instance. But the changes that are done for class variables will be visible to all the instances of that class. This is because the class variables are shared among all instances of the class. Both class variable and member variables have been identified as a member variable of a class.


Hope this will helpful for you!

Regards
Chathuranga Tennakoon

Tuesday, January 1, 2013

Adding the executing order for the Servlet 3 Annotation based Filter classes

welcome to my first post o the year 2013 ;) and i today decided to investigate through servlet 3.0 features.  as you all are aware servlet 3 has a nice feature called annotations. therefore we can minimize the XML based declarations on the web.xml deployment descriptor. today i am going to show a simple demonstration on annotated servlet filters and how to add execution order for those servlet filters.

you can generate simple web application project with  following maven command.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp

one the project is generate, make sure to check and alter the web application deployment descriptor based on the servlet 3 API version . i have post a article about deployment descriptors(web.xml) for different servlet versions   and you can refer that article if you dont know how to do that and what is the purpose of doing that.

after creating the project, add following servlet3 maven dependency for the pom.xml of your project.

then add the following two filters also. you can see that here we are using the annotated servlet filters. 
 FilterOne.java  
FilterTwo.java  

if you need you can add the following servlet class also.  
HelloServlet.java 

you can deploy the web application in the tomcat and access the web application as follows.

http://localhost:8080/sample-servlet3-webapp/hello

then you will get the following result(check the application loggers).
inside the filter one
inside the filter two 
this servlet will be executed after executing the all relevant filters  according to their order 

you can get the full source code from my GitHub account Download Source code through GitHub

Tuesday, July 17, 2012

web.xml deployment descriptor for diffrent sevlet versions

today i am gong to discuss the different web.xml deployment descriptors available for each servlet API versions. hope this might be helpful for you to decide the correct web.xml DD definition base on the servlet API version you are using.

1. Servlet 2.3 Deployment Descriptor

For Servlet 2.3, using a dtd file to validate the XML content. Not recommend to use, consider upgrading to version 2.4 or 2.5.

P.S Maven 3′s quick start web app is still generating this

web.xml -> Namespace = none
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
  <display-name>Servlet 2.3 Web Application</display-name>
</web-app>
 
 

2. Servlet 2.4 deployment descriptor

For Servlet 2.4, using xsd to validate XML content, the most popular web.xml version.
web.xml -> Namespace = http://java.sun.com/xml/ns/j2ee
 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
       http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
       version="2.4">

  <display-name>Servlet 2.4 Web Application</display-name>
</web-app>
 
 

3. Servlet 2.5 deployment descriptor

For Servlet 2.5, using xsd to validate XML content, from this version and onward, the namespace is changed.

web.xml -> Namespace = http://java.sun.com/xml/ns/javaee
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5">

  <display-name>Servlet 2.5 Web Application</display-name>
</web-app>
 
 

4. Servlet 3.0 deployment descriptor

For Servlet 3.0, with xsd validation also, the latest version, but not many people using it.

web.xml -> Namespace = http://java.sun.com/xml/ns/javaee
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
       version="3.0">

  <display-name>Servlet 3.0 Web Application</display-name>
</web-app>
 
 
 
hope this will helpful for you !!!


Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

references 
http://www.mkyong.com/web-development/the-web-xml-deployment-descriptor-examples/

Tuesday, April 10, 2012

WSDL (Web Service Description Language) Binding in WebService

WSDL (Web Service Description Language ) describes the web service message format and the protocol details. WSDL style binding describes how the WSDL details are bounded to the web service.  There are two WSDL binding styles.

1. RPC (Remote Procedure Call) Style Binding
2. Document Style Binding

http://publib.boulder.ibm.com/infocenter/dmndhelp/v6rxmx/index.jsp?topic=/com.ibm.wbit.help.ui.doc/topics/rwsdlstyle.html

Thursday, April 5, 2012

how to change MySQL user password with console(MySQL console)

login to the MySQL  server with the console provided.

mysql  -uroot -p

then  change the database as mysql

use mysql;

then use the following command to change the root password


//the new password of the user whose password should be changed
update user set password=PASSWORD("abc123") where User='root';


Hope this will helpful for you!!!

Thanks and Regards
Chathuranga Tenakoon
chathuranga.t@gmail.com

Monday, April 2, 2012

Transefer PHP class instances as session data using serialization, compression and encryption techniques


The intension of this article is to explain how the PHP class instances(objects) are transferred among PHP pages with the use of sessions. All the objects (including contents) will be serialized, then compressed and encrypted prior to store in the user session.
When retrieving the object from the session variable, you need to remember that it is in the base64 decrypted format. Once you decrypt the object, you will get the object as a deflated string(compressed data). Then you need to inflate (decompress) the deflated string. Then you will get the serialized object(instance). Then you need to deserialized (unserialized) the instance to construct the original instance.

 please refer the below project structure.


we will go through each of the source code files as below.

ConfigData.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
class ConfigData
{

    private  $name;
    private  $email;
    private  $website;


    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setWebsite($website)
    {
        $this->website = $website;
    }

    public function getWebsite()
    {
        return $this->website;
    }

}

?>

TestInterface.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
interface TestInterface
{

public function getInstance();
public function setInstance(ConfigData $cfgData);

}
?>


TestImpl.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
include "interfaces/TestInterface.php";
include "config/ConfigData.php";


class TestImpl implements TestInterface
{
     private $config = NULL;

    public function getInstance()
    {

        return $this->config;
    }


    public function setInstance(ConfigData $cfgData){

        $this->config = $cfgData;
    }

}


?>


testSend.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
session_start();

include "classes/TestImpl.php";

$testImpl =  new TestImpl();

$config = new ConfigData();
$config->setName("chathuranga tennakoon");
$config->setEmail("chathuranga.t@gmail.com");
$config->setWebsite("http://chathurangat.blogspot.com");


$testImpl  = new TestImpl();
$testImpl->setInstance($config);

$_SESSION["TestImplObject"] = base64_encode(gzdeflate(serialize($testImpl)));

?>


testReceive.php
<?php

session_start();

include "classes/TestImpl.php";


$testImpl = new TestImpl();

//printing the session data as it is 
echo "<b>Session Data (Encrypted) </b>[".$_SESSION["TestImplObject"]."]<br/><br/>";

//decrypt the session data with base64 decryption mechanism
echo "<b>Decrypted Session Data in DEFLATE data format (Deflated Session Data) </b>[".base64_decode($_SESSION["TestImplObject"])."]<br/><br/>";

//inflating the deflated string
echo "<b>Inflated Value of the Deflated Value (Unserialized Object) </b>[".gzinflate(base64_decode($_SESSION["TestImplObject"]))."]<br/><br/>";

//unserializing the serialized object
echo "<b>Unserializing the Serialized Object (Serialized Object) </b>[".unserialize(gzinflate(base64_decode($_SESSION["TestImplObject"])))."]<br/><br/>";

//do all above operations in a single statement(line)
$testImpl = new TestImpl();
$testImpl = unserialize(gzinflate(base64_decode($_SESSION["TestImplObject"])));


echo "TestImpl Instance (Serialized Shared Instance) <br/>";

//getting the instance of class ConfigData
$configInstance =  new ConfigData();
$configInstance = $testImpl->getInstance();

//retrieving the object reference ID of the $configInstance
echo "Object Reference ID of the retrieved instance of ConfigData class [".spl_object_hash($configInstance)."] <br/> <br/> <br/>";

echo "<b>Retrieved Member variable data of the instance of ConfigData class</b> <br/><br/>";

echo " <b>Name </b>[".$configInstance->getName()."]<br/><br>";
echo " <b>Email </b>[".$configInstance->getEmail()."]<br/><br>";
echo " <b>Website </b>[".$configInstance->getWebsite()."]<br/><br>";

?>
 


output of the testReceive.php is as follows.




The sample application is available to be downloaded through the following link.

Download Source Code


 Hope this will be helpful for you !!!
 Thanks and Regards
 Chathuranga Tennakoon
 chathuranga.t@gmail.com

Friday, March 23, 2012

Encrypt MySQL data using AES techniques

the data will be encrypted and stored in the database for providing an additional level of security for the data. In MySQL AES(Advanced Encryption Standard) algorithm can be used to encrypt and decrypt the data being inserted and retrieved.

  •  AES_ENCRYPT(data,encryption_key) - the method that can be used to encrypt the data being inserted. 
        e.g:- AES_ENCRYPT('chathuranga','abc123');

  • AES_DECRYPT(encrypted_data,encryptyed_key) 


suppose you need to encrypt and store the username and email of the every user in the database. these encrypted values are stored in the database as binary strings. therefore you must give suitable data types for the columns in the table to accept and hold binary string inputs. therefore we must use varbinary instead of varchar. create the following table in the database.

create table user_table(
user_id int auto_increment primary key,
username varbinary(100),
email varbinary(100));
 

then insert following data into the table created. you can see that  am using AES_ENCRYPT function with cha123 as the key.


insert into user_table values('',AES_ENCRYPT('chathuranga','cha123'),AES_ENCRYPT('chathuranga.t@gmail.com','cha123'));



insert into user_table values('',AES_ENCRYPT('darshana','cha123'),AES_ENCRYPT('chathurangat@lankacom.net','cha123'));


you can see that the data has been stored in a encrypted format. see below screen dump.


 the result of the select query is displayed in the encrypted format. if you need to see the original values (decrypted values) you have to use the AES_DECRYPT function to decrypt the values stored.  the command is as follows.


select AES_DECRYPT(username,'cha123') As username_origianal , AES_DECRYPT(email,'cha123') As email_origianal from user_table;

refer the below screen shot.



 finally try out  the following select statement to understand how to use where clause with an encrypted columns.


select AES_DECRYPT(username,'cha123') As username_origianal , 
AES_DECRYPT(email,'cha123') As email_origianal 
from user_table 
where username = AES_ENCRYPT('chathuranga','cha123');



Hope this will helpful for you!!!

Thanks and Regards,
Chathuranga Tennakoon
chathuranga.t@gmail.com

Tuesday, March 20, 2012

Adapter Pattern


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


interface TargetNumberSorter{
   
   
    public int[] sortIntegerList(int[] arr);
   
   
}



class AdapterNumberSorter implements TargetNumberSorter{
   
   
    public int[] sortIntegerList(int[] arr){
       
       
        //convert array to List<Integer>
        List<Integer> arrList =  new ArrayList<Integer>();
        for(int i=0;i<arr.length;i++){
           
            arrList.add(arr[i]);
        }
 
        //sort List<Integer> with Adaptee
       
        AdapteeNumberSorter ans = new AdapteeNumberSorter();
        List<Integer> sortedList = ans.sortIntegerList(arrList);
       
        int sortedArr[] =new int[sortedList.size()];
       
        //convert List<Integer>
        for(int index=0; index<sortedList.size();index++){
           
            sortedArr[index] = sortedList.get(index);
        }
       
         return sortedArr;
       
    }
   
   
}






class AdapteeNumberSorter{
   
    public List<Integer> sortIntegerList(List<Integer> inputList){
       
       
        Collections.sort(inputList);
       
        return inputList;
    }
   
}





class ApplicationClient{
   
   
    public static void main(String[]args){
       
        int arr[]={45,10,1,46,98,22,30,8};
       
        System.out.println("array before sorting Data ");
       
        for(int i=0;i<arr.length;i++){
           
            System.out.println("index ["+i+"] = "+arr[i]);
        }
       
        System.out.println("array after sorting Data ");
       
       
        TargetNumberSorter tns =  new AdapterNumberSorter();
       
        int sortredArr[] = tns.sortIntegerList(arr);
       
       
        for(int i=0;i<sortredArr.length;i++){
           
            System.out.println("index ["+i+"] = "+sortredArr[i]);
        }
       
       
    }
}