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).
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:
To get a token for this route POST JSON in the following format to http://localhost:5000/token.
and you will get your token:
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 firstname.lastname@example.org 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!