SSO for Your Single Page Application (Part 2/2 — Akka HTTP)

Bartek Andrzejczak
Bartek Andrzejczak
Published in
7 min readDec 6, 2015

In the previous post I’ve shown you how to integrate front-end part of our application with Keycloak as a Single Sign-on server. That is really important, but almost no real application can work without a back-end. That’s why today we’ll delve into the problem of authorizing requests in the server application. If we’re using an application container this job will probably be much easier. Keycloak provides some out of the box adapters for most mainstream servers, so the only thing you have to do is to download them and add a little bit of configuration. That’s a piece of cake. That’s why we’ll look into something different: adding OAuth2 and in particular Keycloak support for Akka HTTP.

Preparations

I want to show you the code as soon as possible, so let me just give you the minimal introduction you need.

As for Keycloak we don’t really need another client besides the one created in the previous post. Normally we would create a bearer-only client, so we can actually differentiate between authorization requests made from the front-end and from the back-end, but that’s not necessary for it to work right now.

As for the application minimal set of dependencies, let’s look at build.sbt:

Dependencies are divided into three groups:

  • akka - Akka-related dependencies. We’ll need base akka library to create an Actor system needed for akka-http. We’ll also need spray-json for akka-http to send some JSON data back to the client.
  • logging - Logging-related dependencies. Nothing special here.
  • keycloak - We’re using keycloak-adapter-core to validate our requests. The problem is, that this library is build mainly with application containers in mind, so we need to fetch some of it’s dependencies by hand.

Token verifier

It looks like we’ve got our setup ready. Let’s go straight into the meat. The first thing we’ll need is something to actually verify if the given token is valid in a provided Keycloak realm. To make it more general and reusable let’s use a trait:

For the purpose of this tutorial let’s say, that verifyToken method will accept a token an return either a Success with user’s preffered username inside or a Failure if authentication failed for any reason. The authentication may take some time, so we’ll use Future here not to block the application.

Because we’re using Keycloak, we’ll need a Keycloak-specific implementation of this trait. Here is is:

The class accepts as its constructor an instance of KeycloakDeployment class which is a part of keycloak-core library. It will tell us where to look for a Keycloak instance. Implementation of verifyToken method is pretty straightforward. We use RSATokenVerifier provided by keycloak-adapter-core which will first check if the token has a valid structure and then send a request to Keycloak to ask whether this token is valid in the application realm. This method will return an AccessToken instance, from which we can extract preferred username. All of this is wrapped into Future.apply method which will take care of asynchronous computation and authorization failures communicated by exceptions.

Extracting token value

With that in place we can go into integrating it with Akka HTTP routing mechanism. It is build on the concept of directives which either fit the supplied request or reject it (which is a simplification, but you get the gist). They can also provide some values. We’d like to have a directive of our own, that would fit the request only if it carries valid authentication token, and that would provide instance of OAuth2Token class consisting of token text and preferred username.

First we’ll need a directive that will fit only requests that carry some authentication token. It would be good if the token could be sent as either header or a cookie. (we’ll tackle this header vs. cookie debate later). Here’s the code for this token extraction directive:

optionalHeaderValueByType and optionalCookie are both methods comming from akka-http and they both return an Directive1[Option[_]] instance. We need to unify it to Directive1[Option[String]] containing token value.

In case of cookie it’s pretty straightforward. We need to map the directive to get to it’s value which is of type Option[HttpCookiePair], which we map again extracting its String value.

For header it’s a bit more complicated. Required Authorization header will have Bearer {token} format. We could either extract the token value with a Regexp matcher or use extractors provided by akka-http. Using a regexp to solve a problem is creating another two, so we’ll go with extractors here. OAuth2BearerToken will do a job for us, giving us String token ready to use.

Last thing that’s left to do is actually joining those two directives into one. Here we’ll go with auth header before a cookie, but we don’t really consider having both the cookie and the header on one request.

Validating request token

Second directive we need to write is directive that will verify the token if it exists on the request and reject the request if it doesn’t. Here it goes:

If the token is part of the request in either header of cookie form, we verify it with tokenVerifier passed to the class as a parameter. Verification is asynchronous, so we need to wait for it to complete using another one of Akka HTTP directives: onComplete. When we’ve got the result of the verification it will be of type Try[String]. Its successful value can be mapped as a provide directive that always fits the requests and provides a given value. If the verification failed we recover by logging the error and rejecting the request. We need to use toDirective explicitly (instead of default implicit conversion) because the type inference doesn’t get that one. After we’ve recovered from any exceptions it’s safe to unwrap Try with get. If there’s no token on the request, we simply reject it.

Putting it all together

How to use what we’ve done so far? Just like we’d use any other directive! Let’s look at the code:

Since we’re using Akka HTTP we’ll need both implicit ActorSystem and ActorMaterializer instances in place. Then we can create instance of our OAuth2Authorization class, that holds authorize directive. We’ll use it with akka.event.Logging and our KeycloakTokenVerifier. KeycloakDeploymentBuilder will be build using keycloak.json saved in the resources folder. We’ve acquired this file in the course of previous tutorial. When we have our authorization object created we can import its contents for the better feels of the API. No we can simply use it writing:

The last line creates an HTTP server and binds our routing (transforming it into Flow with help of ActorMaterializer) to a chosen interface and port. And that’s it!

Testing it with AngularJS

How do we know that it actually works? Let’s put it to test by extending our AngularJS application from the previous post to make an HTTP request to the back-end.

First we need to store a token acquired in the process of logging in to use it in later requests. We’ll do it in the run function defined before:

We add a cookie, that will be added to all the requests made to the server.

Keycloak token have some expiration date, so we’ll need to cover that one by refreshing it from time to time:

When the user loggs out we’ll also need to reset this interval and clear the cookie:

Now we’re prepared to make a request to the server. A little digression here: Since we’re binding client and server applications on a different port, we’d normally have to deal with CORS. To avoid it here we will use JSONP request, which is a regular GET request, which expects, that data coming back from the server will be wrapped in a JavaScript function. Angular will then call this function and retrieve the result. This is why in the line 17 of our main application class we used jsonpWithParameter directive. This directive was once a part of spray which is an ancestor of Akka HTTP, but then went missing. That’s why I had to reimplement it for Akka HTTP here.

Going back on tracks, here’s the code for making the request:

JSON_CALLBACK will be replaced by angular with a name of actual method that it uses and the request will be executed as GET. Now believe me or not, but having Keycloak, Server and Client applications up, this actually works!

If you still don’t believe me, I encourage you to download the source code and see it for yourselves :)

Addendum: Cookies vs. Headers

In this post I’ve used cookies as a mean of storing authorization token. Why the demonized cookies over safe headers? The reason is quite simple. For one thing, I wanted to show you, that it can be done either way — the server can accept both headers and cookies and it will be fine. The other thing is, that even though the cookies are less safe, they work where headers don’t. One such case is image fetching. We could’ve done it with some custom angular directive that downloads image with a simple GET request with the header set and then creates <img> element out of it, but if you want to be able to write <img src="host/someImage" />, you’re basically left with a cookie, because that request will be made by a browser, which doesn’t care about default headers for AngularJS, but it definitely cares for cookies set. That’s all ;)

As usual, the source code is available on GitHub: https://github.com/bandrzejczak/keycloak-angular-akka-http.

--

--