Monday, August 31, 2015

Using OAuth to connect to Google APIs from a Java desktop application

Google uses OAuth for managing authentication and authorization to its APIs. While the flow of action comes naturally in a Web application, it may be confusing for a Desktop a application. The steps for using OAuth is as follow:

           1. Obtaining OAuth credentials from Google Developpers Console
           2. Request a Token
           3. Use Tokens to Authenticate your Requests
           4. Refresh the token when it expires.

While on a Web application you have the possiblity to use redirect and directly store your token on the current session, in a Desktop application you need enter the URL manually in a browser, retrieve the code, enter it, obtain the token and store it on disk.

Let's go through an example of access to Google Calendar API from a Swing application:

First of all, you need to obtain OAuth Client Credentials from Google Developers Console.

The flow is as follows:
- Use the credentials to request a code from Google OAuth server
- Open a browser and copy the code
- Enter the obtained code in the command line as requested by the application
- Obtain the token and store it on disk
- Use it as long as it is valid, else refresh it

The code below illustrates the process:
 /** Authorizes the installed application to access user's protected data. */
   private static Credential authorize() throws Exception {
     // load client secrets
     GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
         new InputStreamReader(GoogleCalendarManager.class.getResourceAsStream("/client_secret_2.json")));
     //If the client secrets/Id are not valid
     if (clientSecrets.getDetails().getClientId().startsWith("Enter")
         || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
           "Unable to authenticate, Please Enter a Client ID and Secret from ");
     GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
         httpTransport, JSON_FACTORY, clientSecrets,
     Credential credential;
     //First Time
     if(flow.getCredentialDataStore().isEmpty()) {
   GoogleAuthorizationCodeRequestUrl url =  flow.newAuthorizationUrl();
     System.out.println("Please enter the URL in your browser: " +;
     System.out.println("Please enter the code: ");
     BufferedReader br = 
                new BufferedReader(new InputStreamReader(;

                String code;
                code = br.readLine();
  //System.out.println("received code " + code);

  AuthorizationCodeTokenRequest accessTokenRequest = flow.newTokenRequest(code);
  TokenResponse response = accessTokenRequest.execute();
     credential = flow.createAndStoreCredential(response, APPLICATION_NAME);
     //After the first time
       credential = flow.loadCredential(USER_ID);
     return credential;

The "client_secret_2.json" is provided by Google OAuth and can be downloaded when the client secrets are set up.

Full example at:

Monday, August 3, 2015

How to secure a Java desktop application using Apache Shiro

Apache Shiro is one of many available Java framework for securing your application. While most of them focus on Web applications, Shiro can be used to secure your Desktop application as well. Shiro focuses on simplicity and can be used even by newbies.

Let's suppose we have users credentials and roles stored in a database, and we want to use Shiro for managing login to the application. Shiro uses the concept of Realm to define the data object that  gives access to user credentials. Since we are accessing user credentials in a database, we will be using JdbcRealm. We need also to define the database queries that will be used to retrieve credentials and roles. Something like: 

//To be adapted to user context
    private static final String AUTHENTICATION_QUERY = "SELECT password FROM users WHERE username=?";
    private static final String ROLES_QUERY = "SELECT access_designation FROM access_level,users WHERE and users.username = ?" ;

Another important aspect of Shiro is shiro.ini which is used for configuration :
# =============================================================================
 #  Realm configuration
 # =============================================================================
 jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
 jdbcRealm.permissionsLookupEnabled = false
 ds = yourpackage.MyDataSource
 securityManager.realms = $jdbcRealm
We need also to define our datasource, which tells Shiro about how to connect to the database.
import com.jolbox.bonecp.BoneCPConfig;
import com.jolbox.bonecp.BoneCPDataSource;

 * @author zakaria
public class MyDataSource extends BoneCPDataSource {
    /** Data source class for retrieving authentication information **/
    public MyDataSource() {
    /* Change as needed */

     * @param config
    public MyDataSource(BoneCPConfig config) {

We are set. We can now define our authentication class:

public class Authenticator {
    //To be adapted to user context
    private static final String AUTHENTICATION_QUERY = "SELECT password FROM users WHERE username=?";
    private static final String ROLES_QUERY = "SELECT access_designation FROM access_level,users WHERE and users.username = ?" ;
    /*** Autenticates a user **/
    public Subject authenticate(String username, String pass) {

		Subject currentUser = null;
		try {

	   Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
			// the key "jdbcRealm" must be the same in the shiro.ini file.
JdbcRealm realm = (JdbcRealm) ((IniSecurityManagerFactory) factory).getBeans().get("jdbcRealm");

			currentUser = SecurityUtils.getSubject();

			UsernamePasswordToken token = new UsernamePasswordToken(username, pass);
		} catch (Exception e) {
		return currentUser;



Finally, we can use our authenticator as needed:

public static void main(String[] args) throws Exception {
		String userName = "someUserName";
		String userName = "somePassword";

		Authenticator authenticator = new Authenticator();
        Subject currentUser = authenticator.authenticate(userName, password);
        	Session session = currentUser.getSession();

        	//Storing some attributes
        	session.setAttribute("Connected", "yes");

        	//Retrieving attributes later on 

            String attribute = session.getAttribute("Connected").toString();

            System.out.println("Connected : " + attribute);

           System.out.println("Could not authenticate user");

Source code: