Friday, February 14, 2014

How to retrieve Facebook profile using Apache Oltu

This tutorial shows you the basic of OAuth using Apache Oltu (Formely known as Apache Amber). We have created a Java Web Application that authenticates the user to Facebook via OAuth 2.0 and retreive the protected resources from Facebook.

Setup :
  • SSL enabled Tomcat Server as we have deployed our Web Application on tomcat. Click here for instruction on How to enable SSL on Apache Tomcat 7.0
  • Registered Facebook Application. Check here for instruction on How to register App on Facebook.
  • Download the OltuClientFB Application from the GIT repository.
  • If you are using Maven then add below dependency or download Apache Oltu client jars :
    <dependency>
      <groupId>org.apache.oltu.oauth2</groupId>
      <artifactId>org.apache.oltu.oauth2.client</artifactId>
    </dependency>

Run the Project :

Check out the project from the above URL, import into the eclipse and Run as a Server.

Navigate your browser to https://localhost:<port>/OltuClientFB. You will see the following page:





Click on the link and it will take you the Facebook page for Authentication :


Once you are login into Facebook, It will ask you to allow the Oauth application to access your private data:



Once you click on “Okay” button. It will display your profile detail like UserId, Name etc.



Code Description :

OAuthServlet.Java

In the Servlet initParams, We have defined the clientId, clinetSecret and the redirectUri, You can change it as per your Apps.
// clientId is 'App ID '
@WebInitParam(name = "clientId", value = "YOUR_CLIENT_ID"),
// clientSecret is 'App Secret'
@WebInitParam(name = "YOUR_CLIENT_SECRET", value = "70ba69525274876dce9697ad183a9051"),
// This must be identical to 'Valid OAuth Redirect URI's'
@WebInitParam(name = "redirectUri", value = "https://localhost:7443/OltuClientFB/OAuthServlet/callback"),})

The Java Web Application act as a third-party website or termed as “client” which operate on behalf of a user. It first sends the request to Facebook which authenticates the user, obtain the user's authorization(i,e Approve/Deny page) and issues an access token which client can use while interacting with the resource server i,e Facebook to access public profile of the user.

End user Authorization request :


Created the End User Authorization Request by providing end-user authorization URI at the Authorization Server (e.g. Facebook), application's client id and a redirect URI in order to receive the authorization code. Apache Oltu has an enum OAuthProviderType for authorization and token endpoints of common OAuth 2 providers like Facebook.

OauthClientRequest authClientRequest = OAuthClientRequest
.authorizationProvider(OAuthProviderType.FACEBOOK)
.setClientId(clientId).setRedirectURI(redirectUri)
.buildQueryMessage();

The above code will produce an OAuth request where all the parameters are encoded in the URL query.

response.sendRedirect(authClientRequest.getLocationUri());

Get Authorization Code from redirect URI :

Once the user grants permission for your client application, then the Facebook will redirects the user to redirectUri with the code in the request parameter.


OAuthAuthzResponse oar = OauthAuthzResponse.oauthCodeAuthzResponse(request); code = oar.getCode();

Exchange OAuth code for an access token :


Apache Oltu has two different classes to parse the access token response. Facebook’s response is not fully compliant with the final version of the OAuth 2 specification, but it can be parsed using the class GitHubTokenResponse.



OauthClientRequest authClientRequest = OAuthClientRequest.tokenProvider(OAuthProviderType.FACEBOOK)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUri).setCode(authorizationCode)
.buildBodyMessage();
//create OAuth client that uses custom http client under the hood
oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(authClientRequest,
GitHubTokenResponse.class);
String accessToken = oauthResponse.getAccessToken();

Get Facebook profile data :

OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest("https://graph.facebook.com/me").setAccessToken(accessToken).buildQueryMessage();
OAuthResourceResponse resourceResponse oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET,
OauthResourceResponse.class);

DisplayFacebookProfile.Java 
This class will display the user profile on the UI.


Summary :

This application demonstrates the basic of OAuth 2.0 using Apache Oltu i,e how to authenticates the user and retreive the protected resources from Facebook.

Resources :

https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart

Code download link:
https://drive.google.com/file/d/0B7WKU816EmtaSUw3UmpsWUljWk0/view?usp=sharing

How to register App on Facebook

Steps to create Apps on Facebook :


Registration Page
  • Enter the Display Name. This is required. 
  • Enter Namespace. (Optional)
  • Choose a Category and then click on Create App button. After verifying captcha It will show you the App ID and App Secret which is nothing but ClientId and ClientSecret . Check below screenshot :




  • Select “Settings” and then click on “Advance” tab.
  • Scroll down and enter your callback URL in “Valid Oauth redirect URIs” and then click on “Save Changes button to save your apps.





Congratulation!!! You have created your Apps on Facebook.

Tuesday, February 11, 2014

How to setup of WSO2 Identity Server on windows

What is WSO2 Identity Server ?

WSO2 Identity Server is an enterprise-ready, fully-open source, lean, component-based solution for facilitating security and provides secure identity management for enterprise web applications, services, and APIs by managing identity and entitlements of the user securely and efficiently.
It helps improve customer experience by reducing identity provisioning time, guaranteeing secure online interactions, and delivering a reduced single sign-on environment. WSO2 Identity Server decreases identity management, entitlement management, and administration burden by including role-based access control (RBAC) convention, fine-grained policy-based access control, and SSO bridging.

Downloading the product :
  • In your Web browser, go to http://wso2.com/products/identity-server.
  • If you are a new user downloading WSO2 products for the first time, register and log in.
  • Once you are logged in, click the Binary button in the upper right corner of the page.

The binary distribution contains the Carbon binary files for both Windows and Linux operating systems, compressed into a single ZIP file.

Installing the Identity Server :

Before installing, You must set your JAVA_HOME environment variable.
  • Download the latest version of the Identity Server as described above
  • Extract the archive file to a dedicated directory for the Identity Server, which will hereafter be referred to as <WSO2_HOME>.

Starting the Server :

To start the server, you need to run the script “wso2server.bat” which is under $WSO2_HOME/bin folder.
Once the server has started, you can see the Management Console by opening a Web browser and typing in the management console's URL. You can check the URL as the last line in the start script's console. Check the screenshot below :






Use “admin” as username and password to sign in to the Management Console.
By default, The session-timeout value is 15 minutes but you can change this in the $WSO2_HOME/repository/conf/tomcat/carbon/WEB-INF/web.xml file as follows:

<session-config>
<session-timeout>15</session-timeout>
</session-config>

Stopping the Server :

To stop the server, press Ctrl+C in the command window or click the Shutdown/Restart link in the navigation pane in the Management Console.


Resources :
http://wso2.com/products/identity-server/

http://docs.wso2.org/display/IS460/WSO2+Identity+Server+Documentation

Tuesday, October 29, 2013

How to substitute dynamic placeholder in properties file

This blog will explain you how can you use replace placeholder with original value in properties file. To achieve this task we will you Java API MessageFormat.

Suppose you have properties file named "welcome.properties" having message :
welcome=Hi {0} , Welcome to {1}
Sample : 

import java.io.File;
import java.io.FileInputStream;
import java.text.MessageFormat;
import java.util.Properties;

/**
 * @author abdul
 *
 */
public class DynamicPlaceholder {

/**
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
File propFile = new File("D:\\juno\\Practise\\src\\com\\waheed\\dynamic\\placeholder\\substitution\\welcome.properties");
Properties props = new Properties();
FileInputStream stream=new FileInputStream(propFile);
props.load(stream);
String message = props.getProperty("welcome");
               // Here the {0} and {1} will be substitute with "Waheed" and "India".
String welcome = MessageFormat.format(message, "Waheed","India");
System.out.println("Your message : " + welcome);
}
}

Output : 

Your message : Hi Waheed , Welcome to India

Monday, October 21, 2013

Junit Test with Mockito

Mockito is a testing framework for Java which allows the creation of Test Double objects called "Mock Objects" for use in automated unit testing in conjunction with framework like Junit. 
For more details, Check here.

This blog will show you step by step working of Mockito.

Step 1 : You need mockito-all and Junit jars into you project classpath which you can download it from here.
If you are using maven, add following dependency into your pom.xml file.

<dependency>
            <groupid>org.mockito</groupid>
            <artifactid>mockito-all</artifactid>
            <version>1.9.5</version>
</dependency>
<dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.11</version>
</dependency>

Step 2 : Below is the main service method which we are going to test using Mockito.

import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Provide methods to work with Employees.
 *
 * @author abdul
 *
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDao employeeDao;

  
    @Override
    @Transactional
    public Employee getEmployee(long employeeId) throws Exception {
        Employee employee = employeeDao.getEmployee(employeeId);
        if(employee == null) throw new Exception("Employee not found");
        return employee;
    }
}

Step 3: Now create the test with Mockito


package com.waheed.spring.hibernate.test;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.waheed.spring.hibernate.Employee;
import com.waheed.spring.hibernate.EmployeeDao;
import com.waheed.spring.hibernate.EmployeeServiceImpl;

@RunWith(MockitoJUnitRunner.class)
public class EmployeeTest {
   
    @Mock EmployeeDao mockDao;

    @InjectMocks EmployeeServiceImpl employeeServiceImpl;
   
    private Employee employee;
   
    @Before
    public void setup() {
        employee = new Employee();
        setEmployee();
    }
   
    private void setEmployee() {
        employee.setId(1);
        employee.setGender("M");
        employee.setCountry("INDIA");
        employee.setAboutYou("CRICKEETER");
        employee.setName("Sachin");
    }
   
    @Test
    public void employeeTest() throws Exception {
        when(mockDao.getEmployee(1)).thenReturn(employee);
        Employee emp =employeeServiceImpl.getEmployee(1);
        System.out.println(emp.toString());
       
        //Verify if getEmployee method was invoked on employeeServiceImpl call
        verify(mockDao).getEmployee(1);
        assertEquals("Tesing",emp.getName(),"Sachin");
    }
   
    @Test(expected=Exception.class)
    public void employeeTestFailure() throws Exception {
        when(mockDao.getEmployee(10)).thenReturn(null);
        Employee emp = employeeServiceImpl.getEmployee(10);
       
    }
}
Step 4 : Let me explain in few words, what's going on in my test class. 
  • As I am testing the EmployeeDao so I have created the mocks for EmployeeDao using @Mock Annotation. 
  • @InjectMocks : Use this annotation on the class you are testing. The mock classes are injected into the @InjectMocks class.
  • To create mocks, we need to add @RunWith(MockitoJUnitRunner.class) annotation to the test class or you can use MockitoAnnotations.initMocks(this) in your class in @Before method. 
  • When(...)thenReturn(...) : It specify what should be returned after the particular method was called. 
  • verify() : It ensure that specified conditions are met.
You can download the above source code from here

References:


Friday, October 18, 2013

Testing REST Client using MockRestServiceServer

Problem : I have a Web Application which is deployed on tomcat server and I needed to write unit test cases which can test all the controllers. Secondly It internally also hits another Web server using RestTemplate that means for the success of all unit test cases both the applications should be up and running. 
 
Solution : After spending some time on Google, I found that Spring provide a new feature “MockRestServiceServer” by which testing a REST Client is simple. This new feature is in Spring 3.2.x but also available in Spring 3.1.x via the extra jar named “spring-test-mvc”. So, You can test your Spring MVC controllers very easy without starting any Web Application.

MockRestServiceServer takes the approach of mocking the server and allowing you to specify expected behavior and responses in your junit test class. It also handles server exception classes.
MockRestRequestMatchers offers many hamcrest matchers to check your request URL, headers, HTTP method, and even json and xpath matchers to check body content. MockRestResponseCreators allows you to easily build both success and error responses.

This blog will show you how the mock server works.

My Configuration :
  1. Spring 3.1.x
  2. Junit 4

Step 1 : Add following dependency in your pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- This is not in Maven Central yet must include Spring snapshot repository -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test-mvc</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<scope>test</scope>
</dependency>

<!-- For testing against latest Spring snapshots -->
<repositories>
<repository>
<id>org.springframework.maven.snapshot</id>
<name>Spring Maven Snapshot Repository</name>
<url>http://maven.springframework.org/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository >
</repositories>

Step 2: The next step is to define a Spring MVC controller that we will be writing unit test for :

@Controller
@RequestMapping("/test")
public class RestController {
private static final Logger LOG = LoggerFactory
.getLogger(RestController.class);
@Autowired
RestTemplate template;
@Autowired
IRestService iRestService;
@RequestMapping(value = "/google", method = RequestMethod.GET)
@ResponseBody
public String hitGoogle() {
LOG.info("Notification : hit google command received from REST");
return iRestService.hitGoogle();
}
}

Step 3: Write Impl class which actually perform REST Client operation to get information from some another end Web application.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import com.waheed.mockserver.service.IRestService;

@Service
public class RestServiceImpl implements IRestService {

private static final Logger LOG = LoggerFactory
.getLogger(RestServiceImpl.class);

@Autowired
RestTemplate restTemplate;

/**
* REST client that makes a call to a URL and handle success and error by
* returning them in error String.
*/
public String hitGoogle() {
LOG.info("Testing google :");
String response;
try {
response = restTemplate.getForObject("http://google.com",
String.class);
LOG.info("Response : {}", response);
} catch (HttpStatusCodeException e) {
LOG.error("Error while testing google", e);
return "FAILED : " + e.getStatusCode();
} catch (Exception e) {
LOG.error("Error while testing google", e);
return "FAILED : " + e.getStackTrace();
}
return response;
}
}
Step 4 : Finally the unit test class that uses Spring-test-mvc to mock the controller that returns the response as String.

import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.client.match.RequestMatchers.method;
import static org.springframework.test.web.client.match.RequestMatchers.requestTo;
import static org.springframework.test.web.client.response.ResponseCreators.withSuccess;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;

import com.waheed.mockserver.controller.RestController;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="file:WebContent/WEB-INF/spring-servlet.xml")
public class TestMockRestServiceServer {

@Autowired
private RestTemplate restTemplate;

private MockRestServiceServer mockServer;
@Autowired
RestController restController;

// Execute the Setup method before the test.
@Before
public void setUp() {
//create a mock Server instance for RestTemplate
mockServer = MockRestServiceServer.createServer(restTemplate);
}

@Test
public void testGoogleSuccess() {
mockServer
.expect(requestTo("http://google.com"))
.andExpect(method(HttpMethod.GET))
.andRespond(
withSuccess("SUCCESS",
MediaType.TEXT_PLAIN));
String response = restController.hitGoogle();
mockServer.verify();
assertEquals("SUCCESS",response);
}
}
Here :
@RunWithSpring(SpringJunit4ClassRunner.class) runs the test with Spring custom runner that will load Spring application context from @ContextConfiguration(locations="file:WebContent/WEB-INF/spring-servlet.xml")

@Before annotation executes the setup method before the test. It will create the mockServer for the restTemplate Instance. 
@Test executes the actual test
    mockServer.expect(requestTo("URL")).andExpect(method(Method Type))
.andRespond(withSuccess("RESPONSE MESSAGE”,”MESSAGE FROMAT LIKE JSON OR XML”));

If the controller hit some URL which has exactly the same URL and method type as we have set above then the spring-test-mvc will mock the response as set above.

Note : You must have observed that in unit test case there are few imports which are static. To find the Static imports in your Eclipse IDE you have to configure a bit. Goto Java>Editor>Content Assist>Favorites and Add

    If using Spring 3.2.x:
    org.springframework.test.web.client.match.MockRestRequestMatchers
    org.springframework.test.web.client.response.MockRestResponseCreators

    If using Spring 3.1.x, the static import classes are named differently:
    org.springframework.test.web.client.match.RequestMatchers
    org.springframework.test.web.client.response.ResponseCreators

Common issue:

java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)

There are few ways to resolve the above issue :
Mockito use Hamcrest 1.1 API in the classpath and Eclipse JUnit 4 distribution also has the Hamcrest Core 1.1 API.
  1. You may get this error when Hamcrest API is invoked from Eclipse JUnit’s and Not Mockito. The solution is change the ordering of the jar files in “Order & Export” tab of Eclipse build path.
  2. Or simply removing the JUnit 4 library also fixes the problem apparently
     (junit and hamcrest will be in the maven deficiencies anyway).
You can download the above tutorial form here. 
 
References :
http://docs.spring.io/spring/docs/3.2.x/javadoc-api/index.html?org/springframework/test/web/client/MockRestServiceServer.html
https://github.com/spring-projects/spring-framework/tree/master/spring-test-mvc/src/test/java/org/springframework/test/web/client/match

Thursday, October 17, 2013

How to create Spring MVC project using Maven and Eclipse


This blog will show you how quickly you can  create a Spring MVC project and get it up and running, using the Maven archetype called spring-mvc-archetype.

Note: First You should verify that the Maven Integration for FTP is already installed in your eclipse, If not first installed and then create a new project.

Steps :
  • In Eclipse IDE, Goto  File > New > Project
  • Select Maven > Maven Project and click Next.
  • Make sure you don’t check the option Create a simple project (skip archetype selection), and click Next. In the next screen,
  • Select Catalog as All Catalogs, Archetype as spring-mvc into the Filter  and select maven-archetype-webapp in the artifact list as shown below :

 

In case, If you don't see the above artifact in your Archtype then Click on "Add Archetype" and Add :
    • Archetype Group Id: co.ntier
    • Archetype Artifact Id: spring-mvc-archetype
    • Archetype Version: 1.0.2
    • Repository URL: http://maven-repository.com/artifact/co.ntier/spring-mvc-archetype/1.0.2\
     
Click Next and Enter Group Id (e.g. Test), Artifact Id (e.g. Test), Version (e.g. 1.0) and Package (com.waheed.test), as shown below :

Click Finish.Finally you have a project structure looks like below:                         

 

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