Integrating Google Calendar into a Wicket Application
Join the DZone community and get the full member experience.
Join For Freei recently integrated google calendar into a wicket application i use at home. as some requirements are atypical i want to describe them before going into too much detail:
- as i use the application only by myself i want to allow anonymous access to my application. if multiple users access your system you have to implement “proper” authentication in your application though.
- for the sake of simplicity i do not care about encrypting keys stored on my disk. however, if you use the code from this post in a real production system with multiple users please do yourself a favor and ensure any keys are stored as secure as possible.
technical options
if you want to use a google api in your application there is a chance that they already provide a client library, which is actually the case for google calendar. i decided to go another route for two reasons:
- as this is yet another rest api, there is no need for a special library and a new api. if i use spring already i can achieve the same result by simply using spring’s resttemplate .
- i just wanted to create, update and delete all-day events with an event title. there is no need for a full blown api that allows all options such as support for recurring events, multiple participants or reminders.
prior to accessing a google api an application needs authorization from users to access their data which is handled by oauth 2. as the application already uses spring for various aspects, spring security oauth 2 was the obvious choice for me as it integrates nicely into the rest of the application.
however, i faced two challenges: first, i needed to integrate wicket and spring security oauth 2 and second, spring security oauth 2 needed some tweaks to work together with my setup.
apart from spring security oauth 2 i use the following libraries/frameworks:
- wicket as web framework
- spring as dependency injection container
- jackson for storing tokens and serializing and deserializing messages to the google calendar api
- gradle as build tool
- jetty as container
i have created a simple demo application which allows you to create an all-day event on any of your calendars. it is available on github .
oauth 2 in less than 100 words
there is plenty of information available on the web about oauth 2, so i just want to describe briefly what oauth 2 does:
using oauth 2 users can grant your application access to their data available through third-party services without providing you the credentials of the accounts you want to access. it involves three parties: your users, your application (oauth 2 client) and the authorization provider (oauth 2 server). apart from being users of your application they are also known to the authorization provider. when users access your application (step 1), it requests permission to e.g. access their data from a third party service (step 2). the authorization provider redirects to a page where users can grant your application access (step 3).

oauth2 authorization scenario (icons courtesy of adam whitcroft )
two great resources for in-depth information about oauth 2 are google’s oauth 2 documentation and rfc 6749 .
oauth 2 for web applications
google’s oauth 2 documentation describes different scenarios which can be used. i assume that you want to use the webserver scenario , and specifically that you want to use “online access” (more on that later). in the webserver scenario the user is redirected to google’s authorization server before the first call of the application to the google calendar api. after the user has granted access, the authorization server redirects the user to your application along with an access token and the application may access the google calendar api with this access token.
getting started
before we dive into the code, we have to register the application with the oauth provider. for google, this is done via the api console . the process is pretty straightforward:
1. create a new project and provide a descriptive name:
2. create a new client id. the client id identifies your application against the oauth provider. be sure to provide a custom redirect url in the second screen.
3. after you have clicked “create” the following overview is presented:
the most relevant pieces for your application are the client id and the client secret. as i have already described, the client id uniquely identifies your application with the oauth 2 provider. the client secret authenticates your application with the oauth 2 provider. if you want to think of traditional username/password based authentication, the client id loosely corresponds to the username of your application and the client secret corresponds to the password of your application with the oauth 2 provider. apparently, these two properties should not be shared.
copy the values for “client id” into the property “google.calendar.client.id” and “client secret” into the property “google.calendar.client.secret” in the file application.properties if you follow along with the demo application.
4. next, request access to the google calendar api for your application in the “services” menu
google calendar access using spring oauth 2
all
accesses
of the demo application to the google calendar api are encapsulated in the class
googlecalendarrepositoryimpl
. it uses an extension of the spring standard interface
restoperations
called
oauth2restoperations
which can handle oauth 2 authorization in addition. similar to the standard implementation of restoperations, resttemplate, spring security oauth 2 provides a oauth2resttemplate. in the demo application, the oauth2resttemplate is configured in
com/github/gcaldemo/calendar/spring-context.xml
. first, let’s have a look at the „oauth:resource“ element there:
<oauth:resource id="google" type="authorization_code" client-id="${google.calendar.client.id}" client-secret="${google.calendar.client.secret}" access-token-uri="https://accounts.google.com/o/oauth2/token" user-authorization-uri="https://accounts.google.com/o/oauth2/auth" scope="https://www.googleapis.com/auth/calendar" client-authentication-scheme="form" />
this definition describes the resources we want to access. apart from the client id and the client secret we have already discussed it also contains the url to which users will be redirected when the application needs their approval to access their data (user-authorization-uri). the “scope” attribute defines the privileges the application wants to acquire. in this case we want read and write access to calendar data as indicated by the url. the proper url can be found in the google calendar api documentation .
whenever the application tries to call the google calendar api, spring oauth 2 will check if the application has a valid access token. this access token is issued by the oauth 2 provider and provided to the application after the user has granted access to its data. however, the access token is only valid for a limited time period which varies across oauth providers. google’s access tokens are currently valid for one hour. after that time period the access token is invalid and users have to grant the application access to their data again.
fortunately, there are multiple means to prevent nagging users continuously:
- the oauth 2 rfc specifies a so called refresh token. the refresh token is sent by the oauth 2 provider along with the first access token. it can be used to obtain a new access token upon expiration of the old one without user intervention. the validity period of the refresh token may be limited and depends on the oauth provider. google’s refresh token is valid until the application explicitly prompts the user explicitly for authorization. note that google sends the refresh token only in the „offline“ scenario. offline means basically that an application can act on behalf of users without the user needing to be present (think batch processes). for more information on the refresh token please refer to the section on refresh tokens in google’s oauth 2 documentation .
- in the online scenario (user is present when your application accesses the google calendar api), google does not send a refresh token but rather stores a cookie on the client’s browser. this cookie will be used instead of a refresh token to prevent repeated explicit approval from the user. as i have hinted earlier, this scenario applies to the demo application.
the demo application provides a simple json based token store which is sufficient for a single user. it is implemented in jsonclienttokenservices , which performs the following tasks:
- it stores the access token in a json file
- it adjusts the expiry_in value: the expiry that is sent from the oauth 2 provider is denoted in seconds from the point in time when the oauth 2 provider has issued the access token. so, if the access token is valid for one hour, the initial value will be 3600 (60 seconds per minute * 60 minutes per hour). however, this is obviously not suitable for persistent storage. therefore, the token store will adjust the expiry accordingly when loading an access token.
the token store is configured along with the access token provider:
<bean id="accesstokenproviderchain" class="org.springframework.security.oauth2.client.token.accesstokenproviderchain"> <!-- redefinition of the default access token providers --> <constructor-arg index="0"> <list> <bean class="org.springframework.security.oauth2.client.token.grant.code.authorizationcodeaccesstokenprovider"/> <bean class="org.springframework.security.oauth2.client.token.grant.implicit.implicitaccesstokenprovider"/> <bean class="org.springframework.security.oauth2.client.token.grant.password.resourceownerpasswordaccesstokenprovider"/> <bean class="org.springframework.security.oauth2.client.token.grant.client.clientcredentialsaccesstokenprovider"/> </list> </constructor-arg> <property name="clienttokenservices"> <bean class="com.github.gcaldemo.calendar.repository.impl.token.jsonclienttokenservices"/> </property> </bean>
after defining both the resource to access and the access token provider, the oauth2resttemplate can be configured:
<oauth:rest-template id="googlecalendarresttemplate" resource="google" access-token-provider="accesstokenproviderchain"/>
integrating spring oauth 2 into wicket
if the application has a valid access token, the oauth2resttemplate performs the api call, otherwise a userredirectrequiredexception is thrown. typically, the oauth2clientcontextfilter, which is part of the spring security chain, should catch this exception and redirect the user to the user-authorization-uri specified earlier. however, by default wicket catches all exceptions that occur in the web application and just dumps them in development mode or provides an error page in production mode. hence, the userredirectrequiredexception will never reach the spring security filter chain. therefore, we have to tweak exception handling by implementing a custom iexceptionmapper:
public class oauth2exceptionmapper implements iexceptionmapper { private final iexceptionmapper delegateexceptionmapper; public oauth2exceptionmapper(iexceptionmapper delegateexceptionmapper) { this.delegateexceptionmapper = delegateexceptionmapper; } @override public irequesthandler map(exception e) { throwable rootcause = getrootcause(e); if (rootcause instanceof userredirectrequiredexception) { //see defaultexceptionmapper response response = requestcycle.get().getresponse(); if (response instanceof webresponse) { // we don't want to cache an exceptional reply in the browser ((webresponse)response).disablecaching(); } throw ((userredirectrequiredexception) rootcause); } else { return delegateexceptionmapper.map(e); } } private throwable getrootcause(throwable ex) { if (ex == null) { return null; } if (ex.getcause() == null) { return ex; } return getrootcause(ex.getcause()); } }
the custom exception mapper has to be created in the application by the exception mapper provider:
public class calendardemoapplication extends webapplication { private iprovider<iexceptionmapper> exceptionmapperprovider; @override protected void init() { super.init(); this.exceptionmapperprovider = new oauth2exceptionmapperprovider(); //details left out - see original class on github } @override public iprovider<iexceptionmapper> getexceptionmapperprovider() { return exceptionmapperprovider; } /** * custom exception mapper provider that integrates the oauth2exceptionmapper into the application. */ private static class oauth2exceptionmapperprovider implements iprovider<iexceptionmapper> { @override public iexceptionmapper get() { return new oauth2exceptionmapper(new defaultexceptionmapper()); } } }
now userredirectrequiredexception will not be handled by wicket but
propagated further up the call stack which allows the
oauth2clientcontextfilter to handle the exception properly. we are
almost done but one last piece is still missing.
system-internal authentication
as i have written in the introduction, i do not want to authenticate
against my own application as i am the only user. however, spring
security oauth 2 expects user credentials within the application prior
to authenticating the application against an oauth 2 server. if we try
to perform a google calendar api call as anonymous user we get the
following trace:
org.springframework.security.authentication.insufficientauthenticationexception: authentication is required to obtain an access token (anonymous not allowed) at org.springframework.security.oauth2.client.token.accesstokenproviderchain.obtainaccesstoken(accesstokenproviderchain.java:88) at org.springframework.security.oauth2.client.oauth2resttemplate.acquireaccesstoken(oauth2resttemplate.java:217) at org.springframework.security.oauth2.client.oauth2resttemplate.getaccesstoken(oauth2resttemplate.java:169) at org.springframework.security.oauth2.client.oauth2resttemplate.createrequest(oauth2resttemplate.java:90) at org.springframework.web.client.resttemplate.doexecute(resttemplate.java:479) at org.springframework.security.oauth2.client.oauth2resttemplate.doexecute(oauth2resttemplate.java:124) at org.springframework.web.client.resttemplate.execute(resttemplate.java:446) at org.springframework.web.client.resttemplate.getforobject(resttemplate.java:214) at com.github.gcaldemo.calendar.repository.impl.googlecalendarrepositoryimpl.loadcalendars(googlecalendarrepositoryimpl.java:45) [...]
as the exception message tells, anonymous users are not allowed to perform oauth 2 operations. therefore, we have to grant access to the application only to authenticated users. this is done by configuring an interceptor in the http security configuration:
<security:intercept-url pattern="/**" access="role_user" />
next, we have to trick spring security oauth 2 by implementing a custom authentication processing filter which publishes a system user with proper privileges to the securitycontext:
//some details omitted - see original class on github public class systemauthenticationprocessingfilter extends abstractauthenticationprocessingfilter { @override public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception, ioexception, servletexception { // populate an internal system user in the security context with proper access privileges. these is typically not // necessary for multi user systems in production as users typically have to authenticate against your // application before using it. authentication authentication = new testingauthenticationtoken("internal_system_user", "internal_null_credentials", "role_user"); authentication.setauthenticated(true); return getauthenticationmanager().authenticate(authentication); } public void dofilter(servletrequest req, servletresponse res, filterchain chain) throws ioexception, servletexception { if (securitycontextholder.getcontext().getauthentication() == null) { securitycontextholder.getcontext().setauthentication(attemptauthentication((httpservletrequest) req, (httpservletresponse) res)); } chain.dofilter(req, res); } }
now, spring security oauth 2 can perform authorization requests properly and we are redirected before accessing the google calendar api for the first time:
after the user has granted the application access to its data we can create an event. note that the calendar drop down is already pre-filled with all google calendars the user has at least write access to:
summary
although a client library for the google calendar api is available it is sometimes feasible to use libraries and technologies that are already used in a project. with a few tweaks i was able to use the google calendar api in a wicket application using spring security oauth 2. the example application on github demonstrates the integration but beware of the limitation that was mentioned above: this setup is primarily suited for single-user applications. if you want to reuse the sample code in a production environment you should use a clienttokenservices implementation backed by a database and use a real implementation of abstractauthenticationprocessingfilter such as usernamepasswordauthenticationfilter .
i hope that this post described in enough detail how to integrate the google calendar api into a wicket application. otherwise, feel free to ask questions in the comments section.
Published at DZone with permission of Comsysto Gmbh, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments