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" />                               
                                                TO
<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.

Download


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.
                        <dependency>
                                    <groupId>org.mockito</groupId>
                                    <artifactId>mockito-all</artifactId>
                                    <version 1.9.5</version>
                        </dependency>

You can add it in gradle too:

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

Implementation:


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);
          when(it.next()).thenReturn("A").thenReturn("B");


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.
                        inOrder.verify(employeeDao).addEmployee(any(Employee.class));
                        inOrder.verify(employeeDao).getEmployee(1);


Spying

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);



Timeouts

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

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