Categories
javascript nodejs

Fastify and token authentication

We will be using Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens.

We will generate a new fastify project via the fastify-cli.

fastify generate fastify-api-auth

The plugin we will use for this is @fastify/bearer-auth. You can install it like so.

npm i @fastify/bearer-auth


Lets create a new route. Inside the routes directory create a new folder named auth and add a new index.js file to it. Here is the code for the new route.

module.exports = async function (fastify, opts) {
  fastify.get('/', async function (request, reply) {
    reply.send('Hello world')
  })
}


Inside the plugins directory lets create a new file and call it auth.js and include the code below.

const fp = require('fastify-plugin')

// Here we have out super secret keys.
const keys = new Set(['a-super-secret-key', 'another-super-secret-key'])

module.exports = fp(async function (fastify, opts) {
    fastify.register(require('@fastify/bearer-auth'), { keys })
})

On line 6 we have our super secret keys hard coded. This is just for testing. They should be coming from an environment variable or a secrets management solution like AWS secrets manager.

Now, lets run our app and give it a test.

npm run dev

Lets run a curl command on our terminal.

curl --location --request GET 'localhost:3000/auth' \
--header 'Authorization: Bearer a-super-secret-key'

You should see the text Hello World. If you pass in a bad key you should see {"error":"invalid authorization header"}.