Don’t leave anything out.

There are nearly endless ways to find information about anything online. As a matter of fact, I am contributing to this mass of knowledge right now. The sheer magnitude of information on every subject can seem to be both a blessing and a curse. Sometimes you can find exactly what you’re looking for right away. Yet, other times it feels as if the internet is deliberately keeping secrets, especially when the information you do find falls short in explaining exactly how something works.

I spent the majority of my day today figuring out how to do something seemingly simple. All I wanted to do was make my application use https everywhere. Simple, right? Yes… and no. My application’s backend uses the Play! Framework. Play! allows one to use either Scala or Java (or both) to build your application. Although I am fairly well versed in Java, I am still a bit of a Scala n00b.

My initial strategy for accomplishing my task was to build something outside of the application altogether. My idea was to setup a nginx proxy which would redirect all http traffic to https. The actual setup of the proxy was simple, but we rely on chef scripts - which I’m not a big fan of although I like the convenience they provide - to automate the deployment of our app. I wasn’t particularly thrilled about the idea of composing automation for setting up the proxy and configuring it, so I decided to put that strategy aside and try something else.

After a bit of research, I discovered that it could be achieved fairly simply programmatically using something called Scala HTTP Filters. I was intrigued by the idea of using these filters, but perhaps because I am still new to Scala, their complete implementation within my application wasn’t very obvious from the few small tutorials/SO posts that I could find. I looked for the Java alternative/equivalent and was disappointed to find that there wasn’t one.

Feeling a bit disheartened, I went about the slow, trudging process of (using mostly trial and error) figuring out how on earth I could integrate a Scala filter into my application. Eventually I figured it out, but not after spending several mind numbing hours trying to fit the puzzle pieces together. For the curious, I’ll include the full details of the solution at the bottom of this post.

Why was it so difficult to figure out? Simple: although there were many explanations online, all the explanations I found were incomplete. I found gists with example code, posts on SO that had multiple answers which all provided slightly different means to the same end and at least a half dozen blog posts which provided code samples as well, but there was no hint as to where the code was meant to integrate into the application as a whole. Let alone any information on how to mix these Scala filters with Java code.

I know that I probably shouldn’t complain. After-all, the information that I did find was very helpful and prevented me from having to solve this puzzle from scratch. My question is simply: why bother posting an explanation of something, when you don’t intend to complete it? Below, you’ll see that the problem of https everywhere can be achieved in Play! in two simple steps.

Now, for the interested, here is how it works:

I created a new Scala Class which looked like this:

package filters

import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class HTTPSRedirectFilter extends Filter{
  def apply(nextFilter: (RequestHeader) => Future[SimpleResult])    (requestHeader: RequestHeader): Future[SimpleResult] = {
    //play uses lower case headers.
    requestHeader.headers.get("x-forwarded-proto") match {
      case Some(header) => {
        if ("https" == header) {
          nextFilter(requestHeader).map { result =>
            result.withHeaders(("Strict-Transport-Security", "max-age=31536000"))
          }
        } else {
          Future.successful(Results.Redirect("https://" + requestHeader.host +   requestHeader.uri, 301))
        }
      }
      case None => nextFilter(requestHeader)
    }
  }
}

Then, to use this in Global.java I added this:

@Override
public <T extends EssentialFilter> Class<T>[] filters() {
    return new Class[] {HTTPSRedirectFilter.class};
}

That’s it. That wasn’t so hard, was it?

 
12
Kudos
 
12
Kudos

Now read this

Writing a Swift App With Firebase

Swift is the latest and greatest from Apple for writing iOS and OSX applications. With any luck it will eventually replace Objective-C as the goto language. One doesn’t need to wait though, as one of the banner features of Swift is the... Continue →