This post has some notes and the code I did while studying nestjs. I started those notes in my first post about nestjs with simple use of the components and a second post as a second step how to use the components. Now, I am going a step forward to use some security resources. More detail about it you can see in the nestjs page. The code used in this post you can find inside the messages-level-3 project.
The Authentication is the guarantee you really are who you say you are. One way to make it safe is not only user and password but use token as well. It returns a token to be used in the next requests to validate the user.
The token can helps to protect the available routes to an authenticated user. The process can be done using the @AuthGuard, creating a Strategy class to config the process to handle the token, and using the guard over the endpoint. The NestJS page shows the complete example to use it.
However, it's possible make it global to all endpoints. For that, it's necessary define on the main module, improve the guard and create a decorator to be used in the endpoints that should skip the authentication.
Authorization
Authorization refers to the process that determines what a user is able to do.
The authorization is regarding define roles to filter what can be access or not. The complete example you can see in the NestJS page.
Encryption and Hashing
Encryption is the process of encoding information. Hashing is the process of converting a given key into another value. [1]
One example is signup a new user. The codes to create the new password are below.
Here is the first example using a random series of numbers and letters, salt, to improve the security. After generate that number, the password and salt are concatenate to create the hash number. The last step is concatenate the result and the original salt value. It will make available to validate the password.
A second version is using exactly what nestjs documentation show.
A third version is using what nestjs documentation show with hash using the library bcrypt.
Helmet
Helmet can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately.
CORS
Cross-origin resource sharing (CORS) is a mechanism that allows resources to be requested from another domain. Under the hood, Nest makes use of the Express cors package.
CSRF Protection
Cross-Site Request Forgery: unauthorized command from a trusted user. A good way to prevent this kind of attack is using tokens.
Nestjs has the package csurf to mitigate this risk. It needs session middleware or cookie-parser.
Rate limiting
The rate-limitingis a common technique to protect applications from brute-force attacks.
In the example, regarding the ThrottlerModule, the 'ttl' attribute is the time to live and the 'limit' is the quantity of request to the 'ttl'. Also, you see the guard used to handle that. Here it is global, but not mandatory. There is possibility, for example, to customize it or use decorators.