
akka-http is an Akka
module, originating from spray.io, for building reactive REST services with an elegant DSL.
pekko-http is an open-source fork of akka-http.
akka-http is a great toolkit for building backends for single-page or mobile applications. In almost all apps there
is a need to maintain user sessions, make sure session data is secure and cannot be tampered with.
akka-http-session provides directives for client-side session management in web and mobile applications, using cookies
or custom headers + local storage, with optional Json Web Tokens format support.
A comprehensive FAQ is available, along with code examples (in Java, but easy to translate to Scala) which answers many common questions on how sessions work, how to secure them and implement using akka-http.
Each akka-http-session module for akka-http has a corresponding pekko-http module, with a different group id
(see bottom of the readme).
What is a session?
Session data typically contains at least the id or username of the logged in user. This id must be secured so that a
session cannot be "stolen" or forged easily.
Sessions can be stored on the server, either in-memory or in a database, with the session id sent to the client,
or entirely on the client in a serialized format. The former approach requires sticky sessions or additional shared
storage, while using the latter (which is supported by this library) sessions can be easily deserialized on any server.
A session is a string token which is sent to the client and should be sent back to the server on every request.
To prevent forging, serialized session data is signed using a server secret. The signature is appended to the
session data that is sent to the client, and verified when the session token is received back.
akka-http-session features
- type-safe client-side sessions
- sessions can be encrypted
- sessions contain an expiry date
- cookie or custom header transport
- support for JWT
- refresh token support (e.g. to implement "remember me")
- CSRF tokens support
- Java & Scala APIs
Example
You can try out a simple example by running com.softwaremill.example.ScalaExample or com.softwaremill.example.JavaExample and opening http://localhost:8080.
SessionManager & configuration
All directives require an (implicit for scala) instance of a SessionManager[T] (or SessionManager<T>), which can be created by providing a server
secret (via a SessionConfig). The secret should be a long, random string unique to each environment your app is
running in. You can generate one with SessionUtil.randomServerSecret(). Note that when you change the secret,
all sessions will become invalid.
A SessionConfig instance can be created using Typesafe config.
The only value that you need to provide is akka.http.session.server-secret,
preferably via application.conf (then you can safely call SessionConfig.fromConfig) or by using
SessionConfig.default().
You can customize any of the default config options
either by modifying them through application.conf or by modifying the SessionConfig case class. If a value has
type Option[], you can set it to None by using a none value in the config file (for both java and scala).
When using cookies, by default the secure attribute of cookies is not set (for development), however it is
recommended that all sites use https and all cookies have this attribute set.
Client-side sessions
All session-related directives take at least two parameters:
- session continuity:
oneOff vs refreshable; specifies what should happen when the session expires. If refreshable
and a refresh token is present, the session will be re-created. See below for details.
- session transport:
usingCookies vs usingHeaders
Typically, you would create aliases for the session-related directives which use the right parameters basing on the
current request and logic specific to your application.
Cookies vs header
Session data can be sent to the client using cookies or custom headers. The first approach is the simplest to use,
as cookies are automatically sent to the server on each request.
However, cookies have some security vulnerabilities, and are typically not used in mobile applications. For these
scenarios, session data can be transported using custom headers (the names of the headers are configurable in
the config).
When using headers, you need to store the session (and, if used, refresh-) tokens yourself. These tokens can be
stored in-memory, or persistently e.g. using the browser's local storage.
You can dynamically decide which transport to use, basing e.g. on the user-agent or other request properties.
Basic usage
Sessions are typed. The T type parameter in SessionManager[T] (or SessionManager<T>) determines what data is stored in the session.
Basic types like String, Int, Long, Float, Double and Map[String, String] (Map<String, String>) are supported out-of-the box.
Support for other types can be added by providing a (an implicit for scala) SessionSerializer[T, String] (SessionSerializer<T, String>). For case classes, it's most
convenient to use a MultiValueSessionSerializer[T] or (MultiValueSessionSerializer<T>) which should convert the instance into a String -> String map
(nested types are not supported on purpose, as session data should be small & simple). Examples of SessionSerializer and MultiValueSessionSerializer
usage can be found here for scala and here for java.
Here are code samples in scala and java illustrating how to create a session manager where the session content will be a single Long number.
The basic directives enable you to set, read and invalidate the session. To create a new client-side session (create
and set a new session cookie), you need to use the setSession directive. See how it's done in java and scala.
Note that when using cookies, their size is limited to 4KB, so you shouldn't put too much data in there (the signature
takes about 50 characters).
You can require a session to be present, optionally require a session or get a full description of possible session decode outcomes.
Check java and scala examples for details.
If a required session is not present, by default a 403 HTTP status code is returned. Finally, a session can be invalidated. See how it's done in examples for java and scala.
Encrypting the session
It is possible to encrypt the session data by modifying the akka.http.session.encrypt-data config option. When
sessions are encrypted, it's not possible to read their content on the client side.
The key used for encrypting will be calculated basing on the server secret.
Session expiry/timeout
By default, sessions expire after a week. This can be disabled or changed with the akka.http.session.max-age config
option.
Note that when using cookies, even though the cookie sent will be a session cookie, it is possible that the client
will have the browser open for a very long time, uses Chrome or FF,
or if an attacker steals the cookie, it can be re-used. Hence having an expiry date for sessions is highly recommended.
JWT: encoding sessions
By default, sessions are encoded into a string using a custom format, where expiry/data/signature parts are separated using -, and data fields are separated using = and url-encoded.
You can also encode sessions in the Json Web Tokens format, by adding the additional jwt dependency, which makes use of json4s.
When using JWT, you need to provide a serializer which serializes session data to a JValue instead of a String.
A number of serializers for the basic types are present in JValueSessionSerializer, as well as a generic serializer for case classes (used above).
You may also find it helpful to include the json4s-ext library which provides serializers for common Java types such as java.util.UUID, org.joda.time._ and Java enumerations.
Grab some java and scala examples.
There are many tools available to read JWT session data using various platforms, e.g.
for Angular.
It is also possible to customize the session data content generated by overriding appropriate methods in
JwtSessionEncoder (e.g. provide additional claims in the payload).
Registered JWT claims support
This library supports all registered claims mentioned in RFC 7519, Section 4.1.
Static claims such as iss (Issuer), sub (Subject) and aud (Audience) can be configured by setting akka.http.session.jwt.iss, akka.http.session.jwt.sub and akka.http.session.jwt.aud string properties, respectively.
Because claims such as exp (Expiration Time) and nbf (Not Before) depend on the time at which the JWT was issued, configuration expects durations instead of fixed timestamps.
Effective claim values are then calculated by adding these offsets to the current timestamp (the JWT's issue time).
The offset values are configured via keys defined under akka.http.session.jwt.exp-timeout and akka.http.session.jwt.nbf-offset.
If exp-timeout is not defined, value of akka.http.session.max-age would be used instead.
iat (Issued At) claim represents issue time and cannot be customized. Although you can decide to include this claim in your tokens or not by setting akka.http.session.jwt.include-iat to true or false. By default, this claim is not included.
jti (JWT ID