Category Archives: Programming

Protect your Play! application with the CSRF filter

Play! 2.1 introduces a new filters API and Cross Site Request Forgery (CSRF) protection.  The CSRF filter is not well documented and it took a while to work out how to enable it in my Play! application.  It took a bit of digging through the Play! source code and looking through the CSRF tests to work out how to use the CSRF filter.  Below is a summary of what is required to protect your Play! 2.1 application with the new CSRF filter.

First of all add the filters module to your app dependencies in appname/project/Build.scala.

import sbt._
import play.Project._

object ApplicationBuild extends Build {

  val appName         = "appname"
  val appVersion      = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    jdbc,
    anorm,
    <strong>filters</strong>
  )
}

Next create appname/app/Global.scala and extend the Global settings so that it uses the CSRF filter.

import play.api.mvc._
import play.api._
import play.filters.csrf._

object Global extends WithFilters(CSRFFilter()) with GlobalSettings

Now the CSRF tests will convey that you need to do the following in all your controllers that return a view with a form post.

def index = Action { implicit request =>
  import play.filters.csrf._
  Ok(views.html.index(CSRF.getToken(request).map(_.value).getOrElse("")))
}

and use the CSRF token in your view template as follows.

@(csrf: String)

@main("Welcome to Play 2.0") {</pre>
<style type="text/css" media="screen"><!--
      label{display: block}

--></style>
<div>
<h2>With token</h2>
<form accept-charset="utf-8" action="@routes.Application.save()?csrfToken=@csrf" method="post">
<label for="name">Name:</label><input id="name" type="text" name="name" value="" />

<label for="age">Age:</label><input id="age" type="text" name="age" value="" />

<input type="submit" value="Continue →" /></form></div>
<pre>
}

Relax you don’t have to call CSRF.getToken() in all of your controllers that present a form.  Fortunately there is a CSRF view helper that takes an implicit token so that you won’t need to set up the token in your controller and pass it to the view.  Instead you just have to declare the implicit token in the view and wrap your post action with the CSRF helper function as follows.

@(signInForm: Form[(String,String)])(implicit token: play.filters.csrf.CSRF.Token)
@import helper._

@implicitFieldConstructor() = @{
    FieldConstructor(bootstrapInput.render)
}

@main(Messages("shopanoptic")) {
    <div class="offset3 span6">
        <div class="well">
            <h3>@Messages("signin")</h3>

            @form(CSRF(routes.Session.authenticate()), 'class -> "form-vertical") {

                @signInForm.globalError.map { error =>
                    <p class="error">
                        <span class="label important">@error.message</span>
                    </p>
                }

                <fieldset>
                    @inputText(
                        signInForm("email"),
                        'placeholder -> Messages("email"),
                        '_label -> null,
                        '_help -> Messages("signin.your.email")
                    )
                    @inputPassword(
                        signInForm("password"),
                        '_label -> null,
                        'placeholder -> Messages("password"),
                        '_help -> Messages("signin.your.password")
                    )
                </fieldset>

                <div class="form-actions">
                    <input type="submit" class="btn btn-primary" value="@Messages("signin")">
                </div>
            }
        </div>
    </div>
}

Now you can protect your web application from one of the OWASP Top 10 security vulnerabilities.

HTML5 for Managers

What is new in HTML5?
HTML5 is a “living standard” that embraces the constantly changing and evolving nature of the web. HTML5 introduces a number of new elements for semantic structure, multimedia, graphics and APIs for connectivity, storage, and geolocation that will enable the next generation of web applications. It also removes presentational elements such as font, strike, big, and applet. This further ensures a clear separation of concerns between the content for a site (HTML), the way it is presented (CSS), and how it interacts and behaves with the user (Javascript).

Why is the media industry getting excited about HTML5?
HTML4 was first published in 1997 with the intent of providing a universally understood language for publishing information for global distribution. HTML5 is the evolution web developers needed to build apps instead of documents. HTML5 enables developers to break free of the limits they were used to when building web applications. Developers now have ways to store information on the device for offline use, have access to media, and can create visuals within the browser using HTML5 technologies. This opens up the potential for video, games, and rich web applications running in the browser on multiple platforms and across many devices without plug-ins.

Lessons learnt with HTML5 Video
In practice using HTML5 video exposes a number of challenges in dealing with an emerging technology. There is fragmented support for video codecs between the main browser implementations. You need to support at least two video codecs (H.264 and WebM or Ogg) in order to play video across most HTML5 compatible browsers. HTML5 video also doesn’t support adaptive bitrate streaming such as HTTP Live Streaming or Smooth Streaming, nor does it support DRM protection schemes for premium video content. For these we will still need to rely on Flash.

Moving forward with HTML5
HTML5 is still a long way off from achieving the W3C Recommendation status. However, Google, Mozilla, Apple, Opera, and even Microsoft are rapidly providing implementations of the new standard. Check out http://html5test.com/ to see what features your browser supports and how it scores out of a total of 475 points. You may be surprised by how much or how little your browser supports of the new specification. For example, the highest scoring browser is Google Chrome 17 (374 points), followed by Mozilla Firefox 11 (335 points), and Opera 11.60 (329 points). Microsoft takes the wooden spoon award for having the lowest scores for IE 6 (25 points), IE 7 (26 points), and IE 8 (41 points). The biggest challenge with developing HTML5 apps is providing support for legacy browsers and dealing with nuances between browsers and versions of browsers. This should be expected as early adopters of an emerging web technology.

Checkbox

Checkbox is now available in the App Store

Checkbox has been unleashed upon the masses and is now ready for sale in the App Store.

icon-appstore Screenshot 2011.01.06 15.25.42 Screenshot 2011.01.06 15.26.48 Screenshot 2011.01.06 15.28.51

Checkbox allows you to take a photo of your task list, add checkboxes to the photo, and track the tasks that you have completed.

Use Checkbox to quickly capture your shopping list on your fridge, the meeting actions jotted on your notebook, or the menu of your favourite restaurant. Then turn the photo into a checklist by adding checkboxes to items in the photo that you want to track. Simply tap on the checkboxes to keep track of tasks that you have previously completed.

Find out more about Checkbox

Estimation Deck

Estimation Deck is now available in the App Store

Estimation Deck is now back in the App Store. Estimation Deck saves you from carrying around a deck of cards for your next Agile estimation session.

estimation-deck-512 IMG_0259 IMG_0260 IMG_0263 IMG_0262 IMG_0261

Estimation Deck provides a set of fibonacci numbers that can be used during an Agile estimation session. This application allows the Agile professional to swipe through the deck of cards until the desired estimate is found for the proposed story. Tapping on the estimate card will flip the card to hide your estimate from your colleagues. Tapping the back of the card will flip the card again to reveal your estimate to the group.

Use the settings to switch between Fibonacci, t-shirt sizes, and powers of 2 decks.

Find out more about Estimation Deck

Persisting managed objects with scalar attributes

Core Data natively supports attributes that are of type NSString, NSNumber, or NSData. You can however use other types with a bit of extra work. If you have an attribute that is a scalar value such as BOOL, you can have your managed object persist it by first converting it to a NSNumber. For example, CheckBox is a NSManagedObject with an attribute called checked that is of type BOOL. BOOL in Objective-C can easily be converted to and from a NSNumber.

The header file contains the BOOL attribute for CheckBox.

// CheckBox.h
#import <CoreData/CoreData.h>

@interface CheckBox : NSManagedObject {
}
@property(nonatomic) BOOL checked;

@end

The implementation file contains a PrimitiveAccessors category for the underlying primitiveChecked value, which stores the checked value as a NSNumber. We then override the accessors and mutators for the checked attribute to convert the BOOL value to and from a NSNumber.

// CheckBox.m
#import "CheckBox.h"

@interface CheckBox (PrimitiveAccessors)
@property (nonatomic, retain) NSNumber *primitiveChecked;
@end

@implementation CheckBox

- (BOOL)checked {
    [self willAccessValueForKey:@"checked"];
    BOOL isChecked = [[self primitiveChecked] boolValue];
    [self didAccessValueForKey:@"checked"];
    return isChecked;
}

- (void)setChecked:(BOOL)isChecked {
    [self willChangeValueForKey:@"checked"];
    [self setPrimitiveChecked:[NSNumber numberWithBool:isChecked]];
    [self didChangeValueForKey:@"checked"];
}

@end

Gradle Android Plugin

I have recently joined a newly formed team developing Android applications at a large telco, and I am pleased to announce that we are using Gradle for our builds. We are using Gradle with the Android plugin, and instantly we managed to build a simple application, run tests, and have it installed on a device. Our build script simply looks like the following, which is all that is necessary to use the Android plugin.

buildscript {
  repositories {
    mavenRepo(urls: 'http://jvoegele.com/maven2/')
  }
  dependencies {
    classpath 'com.jvoegele.gradle.plugins:android-plugin:0.8'
  }
}
usePlugin com.jvoegele.gradle.plugins.android.AndroidPlugin

Of course this is a rather simplistic script, but it does everything I need it to do right out of the box. The Android plugin provides a number of tasks that allow you to build, test, package and sign your application. You can even install the packaged application on a device or emulator by running gradle androidInstall. Make sure to set the property “adb.device.arg” to “-e” for a running emulator or “-d” for a connected device.

There is also support in Hudson to trigger a Gradle script. Hudson has a Gradle plugin that can be installed from the Admin console, and allows you to directly trigger a Gradle script in your project. Otherwise you can create a simple shell script to call the Gradle tool from the command line.

It is also worth noting that both IntelliJ and Eclipse provide support for Gradle and the Groovy syntax. That is if you don’t like using the command line to trigger your builds.

Gradle has allowed us to spend less time setting up our build and continuous integration environment, and more time on actual Android development. Our team has benefited greatly from this boost in productivity.