This tutorial will cover username and password authentication. This is very similar to Basic HTTP Authorization, except in this case, we manually authenticate the user ourselves--the middleware does not handle it for us.

Download the Project

To get started, download the project from Github here. It's very barebones, with a simple User class, as well as a UserController where we will handle the auth. I have also included the Authentication and FluentPostgreSQL packages.

The createUser method in the UserController has already been filled in for us, as the focus on this tutorial is the authentication, not User creation.

Database Setup

I am using Postgres for my database in this tutorial. However, you can also use SQLite (or MYSQL--but I havent used that, so not sure about the config for it)

If you're using Postgres

If you're using Postgres as well, first you'll need to create the database. Simply run the following in terminal:

At 1, we decode the request, and call flatMap on the result. We call flatMap because the result of the User.authenticate call is a future, which is what we will need to return. Since we need to return a future from the closure, we call flatMap, not map.

At 2, we create the password verifier, which will be used by the Authentication package internally to compare our hashed password.

At 3, we use the User.authenticate method, and pass in the username, password, and password verifier. The result of this call is actually an optional future User (Future), so we need to call the .unwrap method to get the actual user object out of it. If the unwrapping fails because of failed authentication, we simply return an HTTP status code of 401 unauthorized.