JSON Web Token with Giraffe and F#

So, you have an endpoint and now you want to secure it. A simple way to do this is by using a JSON Web Token (JWT). Hang tight and I’ll show you how to do this with Giraffe and F# in the following steps.

I will be using VSCode with Ionide and the dotnet-cli version 2.1.3 on Windows. (You can download the latest .NET Core 2.0.4 SDK with everything you need here https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.4-download.md.

First create a new Giraffe web app (if you don’t have the Giraffe template installed just run dotnet new -i "giraffe-template::*" to install it).

dotnet new giraffe -o JwtWebApp

2. Add the package for JWT support.

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2.1 Build the project (to get code completion in VSCode).

dotnet build

3. Add .UseAuthentication() to configureApp.

4. Add authentication to services.

5. Create Models\Models.fs and add the following.

6. Change the routes for the webApp to the following.

7. And add the following above webApp to get a working example.

Now run the project:

dotnet run

and you should be able to visit http://localhost:5000/ without credentials but get a 401 Unauthorized on the http://localhost:5000/secured route.

To get a token for this route POST JSON in the following format to http://localhost:5000/token.

{
"email": "your@email.com",
"password": "your_secret_password"
}

and you will get your token:

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ5b3VyQGVtYWlsLmNvbSIsImp0aSI6ImM4NDRkYzVlLTAzZDQtNGJjYS1iODc0LThlN2E3ZDg2MDAzNCIsIm5iZiI6MTUxMzk0Nzk5OCwiZXhwIjoxNTEzOTUxNTk4LCJpc3MiOiJqd3R3ZWJhcHAubmV0IiwiYXVkIjoiand0d2ViYXBwLm5ldCJ9.yhFAdd9DO5r61--OBa_AfSS9yrCG0bieIA5mQgktVzA"
}

Add the contents of the token to an Authorization header.

Now make a GET request against http://localhost:5000/secured again and you should see the following:

User your@email.com is authorized to access this resource.

The aim here was only to show to get a working example of JWT in action with Giraffe and F#. There are certainly numerous ways to improve this and you should never ever have your secret hardcoded in a source file.

Till next time!

Like what you read? Give David Sinclair a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.