Cookie Authentication in Servant

2017-06-02 | Sergey Bushnyak

In the previous note I described how to create very simple authentification to protect part of your Servant-based API. This note will describe how to use more useful cookie Authentication. In a modern web development API not only part of services to communicate with outer world but also a way to build backend independently of frontend technology. You make API service which transfers raw data and your frontend technology makes use of it. In contrast wit server-based rendering used in older days. Consider common combination React and Servant, Elm and Servant, Reflex and Servant. So if some technology outdates or not fulfill your expectation you can easily switch. It’s very convinient for user not to entry each time credentials when entering site or after page change or reloading. So developers use special files to store that credentials temporarly or other relevent information locally, within your browser. That what’s called authentification cookie6. Of course having plaintext credentials is wrong, so usually they are encrypted. You assign those cookies along with requests to API to confirm your identity. If they are encrypted, we need to have a way to decrypt them, assert with user and give him acces to requested resource.

As Servant have support only for basic auth you’ll need to use another library called servant-auth-cookie available in packages repository - Hackage.

Imports and Extensions

Let’s start by importing some modules and enabling a few language extensions.

Working with cookies is easy, we will need to access three values from handlers: AuthCookieSettings, RandomSource, and ServerKey. For route rendering we need: approot, port, and scheme.


You can defined you own set of session data, we will use very simple credentials from previous note

To encrypt and send the information we need to know how to convert it into a ByteString — binary representation of the data. The servant-auth-cookie package uses the cereal library for serialization, so we need to make Session an instance of Serialize type class:

Credentials check

Here is a function you need to check cookie on requests

and then just run it


You can build project and play with it. Download git repo and build servant-auth-cookie project with stack

and use curl to test

At Kelecorix we also have our own implementation for cookies auth that we use in couple client projects, I describe it as second option, because I might be biased because I created this library. Still want to have more description on it


You can build project and play with it. Download git repo and build servant-auth-secure-cookie project with stack

and use curl to test

Encourage me

If you liked this work, you can reward so I can write more often or simply buy me a tea/beer/donut:

If you want me to write about some specific topic, check about section and send me email with request