Friday, July 7, 2017

Introduction to Spring Boot

Spring Boot is another module provided by Spring Framework which provides RAD (Rapid Application Development) feature to Spring framework. Using boot, we can create standalone Spring based application that you can “just run” in no time and Most Spring Boot applications need very little Spring configuration and it does not require any XML configuration. It uses convention over configuration software design paradigm that means it decrease the effort of developer.

Why Spring Boot?

As we know Spring framework provides flexibility to configure the beans in multiple ways such as XML, Annotations and JavaConfig. With the number of features increased the complexity also gets increased and configuring Spring applications becomes tedious and error-prone.
Spring Boot:
·         Ease the dependency Management, Java-based applications Development, Unit Test and Integration Test Process.
    • Eg: By adding springboot-starter-web dependency to pom.xml file will pull by default all the commonly used libraries such as spring-webmvc, jackson-json, validation-api and tomcat into your Spring MVC applications.
  • Do the Auto Configuration
    • Eg: By Adding above dependency will adds all these libraries but also configures the commonly registered beans like DispatcherServlet, ResourceHandlers, MessageSource etc beans with sensible defaults. Will see JDBC configuration blog in next blog.
  • Support for Embedded Servlet (Tomcat, Jetty )
    • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • Easy to develop Spring Based applications with Java or Groovy and it reduces lots of development time and increases productivity. It also avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • Easy to integrate Spring Boot Application with its Spring Ecosystem like Spring-jdbc, Spring-orm, Spring-data-jpa, Spring security etc.

Spring Boot Components

·         Spring Boot Starter

    • Spring boot starter are just JAR Files or set of convenient dependency descriptors which we can include in our application to makes development easier and faster. It follows a naming pattern like: spring-boot-starter-*, where * is a particular type of application. This naming structure is intended to help when you need to find a starter. For example, if we want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project.

·        Spring Boot AutoConfigurator

·   It used by Spring Boot Framework to provide “Auto-Configuration. It attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database.
·      You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configurationclasses.

·        Spring Boot Actuator

·         It is used to expose different types of information about the running application – health, metrics, info, dump, env etc.
·         We can choose to manage and monitor our application using HTTP endpoints, with JMX or even by remote shell (SSH or Telnet). Auditing, health and metrics gathering can be automatically applied to your application.
·         To start using the existing actuators in Boot – we’ll just need to add the spring-boot-actuator dependency to the pom:

·        Spring Boot CLI

·         Tool to run and test Spring Boot applications from command prompt. When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot AutoConfigurate components to resolve all dependencies and execute the application.
·         It internally contains Groovy and Grape (JAR Dependency Manager) to add Spring Boot Defaults and resolve all dependencies automatically.

·        Spring Boot Initilizr

·         It is a web tool which is provided by Spring on official site using which Spring Boot project can be created by providing project details. Check here in depth details.

That’s it all about Spring Boot Framework. Will add few more blogs for depth details.

Wednesday, April 12, 2017

Shibboleth Idp with External Authn Configuration

Shibboleth Idp comes with by default various flows like UsernamePassword, Mfa, X509, Kerberos, Spengo and various others flow but today I am going to discuss in details about one more flow which is also provided by Shibboleth Idp itself i.e External Flow

Use case:

Shibboleth Idp supports external Authn flow using which specific requirement can be fulfilled like your authentication database resides at some other location or some other servlet will do the authentication on the Idp’s behalf like authentication should be done at Facebook or Google side. All such scenario can be easily handled using External Authn flow.
Shibboleth team has already created document for the same which you can read it over here. I am writing this document to explain it in more details with example.

There are few predefined steps that we need to follow to add new custom flow in Shibboleth Idp as per Shibboleth guidelines. Let’s assume we have to create new flow named “Authn/Custom” in Shibboleth Idp. 

Here are the steps:

  • Copy opt\shibboleth-idp\conf\authn\ external-authn-config.xml and change it to custom-authn-config.xml and keep it under the same directory i.e. “opt\shibboleth-idp\conf\authn”.
  •  Replace all ‘External’ with ‘Custom’ in  custom-authn-config.xml file like 

<bean id="shibboleth.authn.External.externalAuthnPath" class="java.lang.String"
        c:_0="contextRelative:Authn/External" />                               
<bean id="shibboleth.authn.Custom.externalAuthnPath" class="java.lang.String"
        c:_0="contextRelative:Authn/Custom" />

  • Copy files from system to flow folder:

            cp system/flows/authn/external-authn-flow.xml flows/authn/Custom/Custom-flow.xml
            cp system/flows/authn/external-authn-beans.xml flows/authn/Custom/Custom-beans.xml

           Note: Make sure the name of the folder should be same as flow name. over here it is Custom  and Replace all ‘External’ with ‘Custom’ and edits the correct path too in both files.

  • Create a java project and create new Servlet CustomAuthnFlowServlet”. Servlet should contain final String key= ExternalAuthentication.startExternalAuthentication(httpRequest) and ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse) and the authentication logic should be added between this statement and If you are doing any redirect then make sure you should persist the key as startExternalAuthentication & finishExternalAuthentication require the same key.
One more point principal should be set as httpRequest.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, username) if you want to retrieve at Shibboleth SP side and in case of error mapped it with AUTHENTICATION_ERROR_KEY. httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, AUTHN_EXCEPTION);
  •  Add new Servlet mapping to web.xml file of Shibboleth Idp.

  •  Add your custom exception that we have created in our Servlet in  opt\shibboleth-idp\conf\authn\authn-events-flow.xml.
  •  Add below snippet to opt\shibboleth-idp\conf\errors.xml

<entry key="CustomException" value-ref="shibboleth.SAML2Status.AuthnFailed" />
        <entry key="AnotherException" value-ref="shibboleth.SAML2Status.AuthnFailed" />

Note: Map your Exception to correct value-ref as incase of error Idp will send this error Response to Shibboleth SP.
  • Register Custom Auth flow in conf/authn/external-authn-config.xml

  • Set idp.authn.flows as Custom (idp.authn.flows=Custom)
  • We can retrieve Principal at Shibboleth IdP side by adding below snipped in attribute-resolver.xml.
We are done here. Restart Shibboleth and hit target URL and you will see the SSO happening using your custom flow. Please feel free to comment or mail me for any queries.

Happy Coding!!!

Wednesday, April 5, 2017

Default and Static methods in Java8

Java 8 introduces a new concept of default and static method implementation in interfaces. Before Java 8, interfaces could have only abstract methods but now It allows the interfaces to have methods with implementation without affecting the classes that implement the interface and provides backward comparability so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class.

Eg: Now List or Collection has forEach method declaration which is only possible because of default declaration. 

Default Method:

The default methods are also known as defender methods or virtual extension methods and are defined inside the interface and tagged with default. These methods are non-abstract methods.

What about Multiple Inheritance?

As we know adding method definitions in interfaces can add ambiguity in multiple Inheritance and if a java class implement multiple interfaces and each interface can define default method with same method signature, then the inherited methods can conflict with each other.
Let’s create another interface with same default method, in below image you can see that AnotherInterface also has default method multiply.

Java 8 handle this issue at Compile type as it will result in a compilation error and can be resolved by overriding the default method or by implementing class should explicitly specify which default method is to be used.

Static Method:

An interface can also have static helper methods from Java 8 onwards and it is similar to default method except that we can’t override them in the implementation classes.

Difference between default methods and abstract class

·         Abstract class can hold state of an object. It can have constructors and member variables.
·         interfaces with Java 8 default methods cannot hold state. It cannot have constructors and member variables.
·         You should still use Abstract class whenever you think your class can have state or you need to do something in a constructor.
·         Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implementor classes. 
      You can download the source code from GitHub.
Happy Learning!!

Monday, March 13, 2017

Mocking in Java using Mockito

Before talking about Mockito Framework. Let’s see why do we need it at the first place and how it can be helpful.

Last year, I was working on one project which talks to other third party services as well as with the database connection and to test the functionality of my application, third party application should be up and running. There can be a chance where all these services might not available during unit testing.

As you can see, your application is completely dependent on other application and what if:
  • Third party application is down
  •             You cannot connect to database to test your functionality

At such situation, mocking becomes a natural solution for unit testing. Using Mockito, you don’t really need a database connection. You just need a mock object that returns the expected result.

Mockito: Introduction

Mockito is a mocking framework, the JAVA-based library that is used for effective unit testing of JAVA applications. It lets you write beautiful tests with a clean & simple API and used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing like we don’t require a database connection or properties file read or file server read to test a functionality. A mock object returns a dummy data corresponding to some dummy input passed to it.

It facilitates creating mock objects seamlessly and uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but the proxy for actual implementations.


You can download the JAR file and place it in your project class or If you are using Maven, then you need to add its dependency in the pom.xml file, as shown below.
                                    <version 1.9.5</version>

You can add it in gradle too:

repositories { jcenter() }
dependencies { testCompile "org.mockito:mockito-core:2.+" }


Mockito provides various Annotation/Class/Function using which we can integrate mock object into out JUNIT test cases.

I’ve uploaded one tutorial on GITHUB which we will refer it to here to understand the behavior/implementation of Mockito framework.

In EmployeeServiceTest_Annotation Class, I am invoking employeeServiceImpl.addEmployee(employee) to add the employee object and expecting long Id after the creation of object into the database. This API internally call employeeDao object to persist the data into the database and get the results.
Over here, employeeServiceImpl is the class in which we will inject the employeeDao mock object.

Let’s start implementing it:

Mockito supports the creation of mock objects using the static mock() method or using @Mock annotation and to use this annotation, we must invoke the static method MockitoAnnotations.initMocks(this) or use @RunWith(MockitoJUnitRunner.class) to populate the annotated fields.

@InjectMocks: it is used to create and inject the mock object.
@Mock: It is used to create the mock object to be injected

Adding behavior to mock object:

Mockito provides when(… .).thenReturn(… .) method to configure which values should be returned at a method call based on specific condition. It will return a value once it matches with a condition.

Eg: when(employeeDao.addEmployee(any(Employee.class))).thenReturn(1L);

It will return 1 whenever we invoke addEmployee(…) with any Employee object.
If you specify more than one value, then it will return in the order of specification until the last one is used.

Iterator it= mock(Iterator.class);

Verify the calls on the mock objects

Mockito provides another method called verify() which is similar to When() but does not check the result of a method but it checks that a method is called with the right parameters. 

Eg: verify call to employeeDao to make sure it get called and limit the method call to 1, no less and no more calls are allowed
            verify(employeeDao, times(1)).addEmployee(any(Employee.class));

Exception handling

Mockito provides the capability to a mock to throw exceptions so exception handling can be tested.

Eg: add the behavior to throw exception
                        doThrow(new Exception("Employee not found")).when(employeeDao).getEmployee(2);

Ordered Verification

Mockito provides Inorder class which takes care of the order of method calls that the mock is going to make in due course of its action.
Eg: Create an inOrder verifier for a single mock

                        InOrder inOrder = inOrder(employeeDao);

            // following will make sure that add is first called then subtract is called.


Mockito provides an option to create spy on real objects. When a spy is called, then the actual method of the real object is called.

Eg:  create a spy on actual object
                        employeeDao = spy(spyEmployeeDaoImpl);


Mockito provides a special Timeout option to test if a method is called within its stipulated time frame.

Eg: Verify call to add employee method to be completed within 100 ms
                        verify(employeeDao, timeout(100)).addEmployee(any(Employee.class));

You can download the source code from GITHUB.

Happy Coding..!!!

Wednesday, February 22, 2017

OAuth vs SSO: Which One Should I Use?

Currently, I am working on one project which provided me a lot of opportunities to learn about OAuth 2.0 and SAML and better understanding on which one to choose for SSO strategy.
I am choosing this topic because most of the people get confused between these two. While they have some similarities but they are very different too and to put it one line. I would say “OAuth is not Single Sign-On”

What is the difference between OAuth 2.0 and SSO?

OAuth (Open Authorization) is a standard for authorization of resources. It does not deal with authentication. It allows secure authorization in a simple and standard method from web, mobile and desktop applications.

If you try to log into Stack Overflow using Facebook, you’ll be redirected to Facebook’s website and will see something like the following:

Once authenticated with Facebook, it will ask for Stack Overflow’s permission to access your resources like your name, Email id, Profile picture and so on. This is an authorization request like what Stack Overflow can do and what cannot do?

SAML: Security Assertion Markup Language is an XML-based open standard data format for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider. It is an umbrella standard that encompasses profiles, bindings and constructs to achieve Single Sign-On (SSO), Federation and Identity Management.

SSO is an authentication/authorization flow through which a user can log into multiple services using the same credentials.
For instance, at your company where we have various applications like leave application, lunch application, career application and so on and we can configure all these applications to one Active Directory for authentication. Another example can be Atlassian account where you once logged in can use their other applications like Bamboo, JIRA, Confluence and so on.

Both examples represent SSO.

One of the main benefits to using SSO is that your users have only a single account and password to remember which gets them into all of their services.

Conclusion: When Should I Use Which?

  • If your use case requires a single account to log into many applications, then go with SSO like your internal company applications.
  • If your use case involves providing access (temporarily or permanent) to resources (such as accounts, pictures, files etc.), then use OAuth.
  • If your use case requires a centralized identity source, then use SSO.
  • If your case requires to have accounts on many different services, and selectively grant access to various services, use OAuth

Friday, February 17, 2017

Set up Shibboleth SP as a SAML 2.0 service provider with G Suite


  1. Basic understanding of SAML 2.0, SSO and Shibboleth SP.  
  2. SP setup up and working on your instance.
  3. Must having administrator account to register your SP on G suite

G Suite setup:

  • Login to using your administrator account.
  • Click Security > Set up single sign-on (SSO)
  • Click the Download button to download the Google IdP metadata and the X.509 Certificate
  • Now click on Apps > SAML apps.
  • Select the Add a service/App to your domain link or click the plus (+) icon in the bottom corner. The Enable SSO for SAML Application window opens.
  • We have already downloaded the certificate and Idp Metadata, click NEXT
  • On the Basic application information window, Enter the Application name and Description values.
  • In the Service Provider Details section, enter the following URLs into the Entity ID, ACS URL, and Start URL Fields:
    1. ACS URL
    2. Entity
    3. Start URL:
Note: You can get the ACS URL and entityID by hitting https://your-domain-name/Shibboleth.sso/Metdata. It will download the Shibboleth SP metadata file containing all the URLs like entityID in the first few lines and ACS URL which is nothing but AssertionConsumerService URL having SAML 2.0 HTTP-POST binding.
    <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="" index="10"/>
  • Leave Signed Response unchecked. When the Signed Response checkbox is unchecked, only the assertion is signed. When the Signed Response checkbox is checked, the entire response is signed.
  • The default Name ID is the primary email and select EMAIL as Name ID Format.
  • Click Add NEW MAPPING and then add EMAIL and choose Basic information and Email from 2nd and 3rd drop down list.
  • Click Finish.
  • Now go to again on Apps -> SAML apps and select your APPLICATION.
  •  At the top of the gray box, click More and choose:
    1. On for everyone to turn on the service for all users (click again to confirm).
    2. Off to turn off the service for all users (click again to confirm).
    3. On for some organizations to change the setting only for some users.

Configured G Suite details in your Shibboleth SP

  • Drop the downloaded Google Idp metadata to opt\shibboleth-sp\etc\shibboleth directory.
  • Open Shibboleth2.xml file and add below snippet
    • <MetadataProvider type="XML" file="C:\opt\shibboleth-sp\etc\shibboleth\<GOOGLE_IDP_FILENAMExml>"/>    
  • Restart Shibboleth.

 Verify that SSO between G Suite and Zendesk is working

  • Close all browser windows.
  • Open and attempt to sign in.
  • You should be automatically redirected to the G Suite sign-in page or if you are having discovery page then it will come under drop down menu
  • Enter your sign-in credentials.
  • After your sign-in credentials are authenticated you're automatically redirected back to your Application.

Happy coding..!!!

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!!!

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...