Authentication and Authorization
We will look at how to set up authentication and further authorize the requests
Although these two words sounds similar, they have quite disctinct functions. Authentication is the term used to verify the identity of a user, while authorization allows the verified identity access to the resources.
For authentication, we will be using the
/login endpoint we defined earlier.
In the previous lesson, we decided to hash the password with theBcrypt algorithm. Although this has been the defacto standard for password hashing since the early 2000s, there are more modern and secure hash algoritms used today with newer applications. In 2015 a new hash algorithm was created namedArgon2 which is supposedly more secure, and it is generally recommended to use this algorithm when creating new applications.
For Deno, there are modules for multiple hashing algorithms, amongstbcrypt. Initially we were going to use Argon2, but due to a lack of standardisation for password hashing for Deno, we will opt for Bcrypt as it is more stable.
The login endpoint#
Let's look at the login endpoint, so that we can authenticate a user against a Duck. In this course, we will be usingJWTs, which we will fetch once during the login request, to then pass along in the header for all authenticated endpoints.
Start by creating a
getByUsername method for our
With this method, we can now get a Duck via its
username instead of its
which will help us when logging in.
Now we can add a
With a similar start as the
create method, we continue using the newly created
getByUsername method before verifying the password with
bcrypt. If the login
credentials are valid, we accept the login and return the record to be used in
Time to add a dependency again!
We now added
jose, the Deno
JSON Web Almost Everything to quote the module.
This module helps us with the creation and validation of JWTs, but it also
includes a lot of other JSON goodies if you need that.
Now we have to create a new type in our
main.ts amongst our other helper
This will add a custom
did (duck ID) property to our default JWT object, and
allow us to indicate which user is making the request.
Before we get into the nitty gritty of authorization and login, we need to add
two helpers in the
Here we are using the nativeWebCrypto API
to generate a