Tuesday, February 14, 2017

Singleton Class Vs Singleton bean scope

I have seen people getting confused between singleton scope vs singleton design pattern. Basically, there is a bit difference between these two.

Singleton scope: The spring support five different scopes and it is used to decide which type of bean instance should be returning from Spring container back to the caller. One of the scope is Singleton and the by default scope too. It returns a single bean instance per Spring IoC container.

<bean id=”object1” class=“com.package.classname”/>

When I said, single bean instance per spring Ioc Container i.e. you will always get the same object regardless of the number of call of the same bean but if you declare another bean for the same class then you will get another object for another bean.

Let’s understand this with an example:

<bean id=”object1” class=“com.package.classname”/>
<bean id=”object2” class=“com.package.classname” scope=”prototype”/>
<bean id=”object3” class=“com.package.classname”/>

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(APP_FILE);
Classname name1 = (Classname) context.getBean(“object1”);
Classname name2 = (Classname) context.getBean(“object2”);
Classname name3 = (Classname) context.getBean(“object3”);


name1==name1 // true, object1 is singleton, calling again n again will give the same object.
name2==name2 //false, object2 is prototype, calling again n again will give the different object
name1==name3 // false, object1 & object3 is singleton but two different bean.

So, the question arise how will you achieve the Singleton design pattern in Spring?

Spring framework provides facility to inject bean using factory method i.e. that returns an instance of its own class and can be used in singleton design pattern.

public class Singleton {
         
                private static volatile Singleton instance = null;
                private Singleton(){        
                }
                                public static Singleton  getInstance(){
                                if(instance == null) {
                                                synchronized (Singleton.class) {
                                                                if(instance == null){
                                                                                instance = new Singleton();
                                                                }
                                                }
                                }
                                return instance;
                }
           }

<bean id="object4" class="com.package.Singleton" factory-method="getInstance"/>
       <bean id="object5" class="com.package.Singleton" factory-method="getInstance"/>
Singleton singleton1= (Singleton) context.getBean(“object4”);
Singleton singleton2= (Singleton) context.getBean(“object5”);

singleton1==singleton1 // true, object1 has singleton scope, calling again n again will give the same object.
singleton1==singleton2 //true, Class is a singleton and we are getting an object from getInstance using factory-method.

Conclusion: Singleton scope is a bit different from a single design pattern, Returns a single bean per Spring Ioc Container whereas singleton design pattern will always return the same object.
Singleton scope can be useful where you are creating multiple datasource in your application where each datasource point to a different object.

You can download the code source from my GitHub repository.

Happy coding!!!




Friday, January 13, 2017

How to uinstall MySQL completely from Windows OS?

I was running some script which did some changes to my database and corrupted my root permission. Tried so many things but didn't work out.

Finally, I decided to uninstall the MySQL from my instance and install a new one but again it was not an easy job as MySQL stores file at the various locations that you have to removed manually before starting from the scratch.

Simple steps to uninstall MySQL:

  1. Stop MySQL services and remove services by executing below command in command prompt (Start it as Administrator)
    1. Net stop MySQL
    2. Sc delete MySQL
  2. Uninstall MySQL program from the control panel.
  3. #2 will uninstall the program but will not remove all the files from your machine which we have to do it manually.(Removing all files will remove existing database. Take the backup, if you need it in future.)
    1. C:\Program Files\MySQL
    2. C:\Program Files (x86)\MySQL
    3. C:\ProgramData\MySQL
    4. C:\Users\<USERNAME>\AppData\Roaming\MySQL
  4. Restart your instance and install it again.
Happy coding..!!!


Friday, December 16, 2016

What is JSON Web Token?

1. Overview

JSON Web Token or JWT (jot) for short is an open standard (RFC 7519) that defines a compact, URL-safe means of representing claims to be transferred between two parties.  The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

2. Structure

The compacted representation of a signed JWT is a string that has three parts, each separated by a dots (.) :

Eg: 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0
.
Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI

Each section is Base64Encoded and the first section is called header, the second section is payload and the third section is Signature.

2.1 Header

It consists of two parts: Hashing algorithm (HMAC SHA256 or RSA) and type of the token and to form the first part of the JWT, you need to do Base64Url encoded.

Eg:
{
  "alg": "HS256",
  "typ": "JWT"
}


2.2 Payload

Payload contains the Claims. JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT i.e. Data to be shared between the applications.
Eg:
{
  "sub": "Abdul",
  "iat": 1234567890,
  "exp": 1234567890,
  "nbf": 1234567890,
  "iss": "http://waheedtechblog.in",
  "scope": ["read","write"],
  "admin": true
}

There are three types of claims: reserved, public, and private claims.

2.2.1 Reserved Claims

These are standard predefined claims defined in the specification which can be used to provide a set of useful claims. Some of them are : 
a. "iss" (Issuer) Claim
b. "sub" (Subject) Claim 
c. "aud" (Audience) Claim
d. "exp" (Expiration Time) Claim
e. "nbf" (Not Before) Claim
f. "iat" (Issued At) Claim
g. "jti" (JWT ID) Claim  


2.2.2 Public Claims

These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.


2.2.3 Private Claims

  All the custom claims come under private claims and it is created to share information between parties that agree on using them.
{
"scope": ["read","write"],
 "admin": true
}

2.3 Signature

To create the signature part, you have to take the encoded header, the encoded payload, and a SECRET_KEY, the algorithm specified in the header, and sign that.
Eg:
if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

You will get the below JWT token if you combine above header and payload and will use secret as SECRET_KEY.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0.Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI


3. How do JSON Web Tokens work?


1. Browser will log in to Authorization Server via username/password

2. Authorization Server will authenticate the user and will create the JWT token signed by its key and will return in the response.
3. Now, Browser will access the Application Server by JWT token as Authorization bearer <token> in the header.
4. Application Server will verify JWT using secret key (In such scenario, Key must be shared between Authorization Server and Application Server), Decode the String, verify the claims and will return the response.


4. Open Source libraries:

There are already open source libraries available in the market using which you can create and verify the access token. 
Source code for implementation of above library can be downloaded from GITHUB

5. Conclusion:

We went over what JWT are, how they are created and validated, and how they can be used to ensure trust between an application and its users. This is a starting point for understanding the fundamentals of JWT and why they are useful. 

6. References:



How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...