Basic Authentication in Servant

2017-06-01 | Sergey Bushnyak

Servant is very powerful abstraction for building typesafe REST API. While building APIs is fun, but often we need to protect some parts of the API with access available only to verified users. Until version 0.5 there was no support for such functionality. Now we can enjoy out of the box feature for basic authentification and generalized types to roll-out your own authentification schemes. This short note describes basic auth and in following I will explain how to create digest, cookie, token, session authentifications.

Basic Authentication

Basic authentification is very weak protection and you should use it only via secure connection - https, and as temporary measure when you need quick implementation. For example, when doing prototype or as fallback option in case of other method failure.

Your single point Api will be transformed in 2 types in case you want to have some methods still public. Consider following example, we have 2 methods to get Poll data and send when you want to create a new one.

transformed into

Along with BasicAuth combinator handler in version 0.5 was introduced class Context which helps to forward appropriate credentials to handlers. All you need is to add BasicAuth combinator before protected API description. Handlers will look like

Simple function to check user credentials looks like this

And run with

Testing

You can build project and play with it. Download git repo and build servant-auth-basic 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