17.1. Authentication and Authorization in NodeJS APIs: Authentication with JWT
Authentication and authorization are crucial elements in creating APIs in NodeJS. They guarantee the security of the data manipulated by the API, allowing only authorized users to access certain resources. This ebook chapter will focus on authentication with JWT (JSON Web Tokens).
What is JWT?
JSON Web Tokens (JWT) is an open standard (RFC 7519) that defines a compact, self-contained way to pass information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Why use JWT for Authentication?
JWTs are a good choice for authentication for several reasons. First, they are stateless. This means we don't need to store session information on the server or in a database. Instead, all necessary information is stored in the token and sent to the server on every request. This allows our application to be scalable and easy to manage.
Secondly, JWTs are compact and can be sent via a URL, in an HTTP header, or in a cookie. This makes them very convenient for authentication, especially in single page applications (SPA).
How does JWT Authentication work?
Authentication with JWT usually involves the following steps:
- The user sends his credentials to the server.
- The server checks the credentials and, if they are valid, generates a JWT that is sent back to the user.
- The user stores the JWT in some way (for example, in a cookie or in local storage).
- The user sends the JWT on each subsequent request to the server.
- The server checks the JWT and, if valid, processes the request.
- If the JWT is not valid (for example, it has expired), the server rejects the request.
Implementing Authentication with JWT in NodeJS
To implement JWT authentication in NodeJS, we need the jsonwebtoken package. We can install it using npm:
npm install jsonwebtoken
Once the package is installed, we can use it to generate and verify JWTs. Here is an example of how we can do this:
const jwt = require('jsonwebtoken');
// Generate a JWT
const token = jwt.sign({ id: user.id }, 'your-secret-key', { expiresIn: '1h' });
// Verify a JWT
try {
const decoded = jwt.verify(token, 'your-secret-key');
console.log(decoded.id); // will print the id of the user
} catch (err) {
console.error('Invalid token');
}
The jwt.sign() function generates a JWT. It takes three arguments: the payload (an object that contains the information we want to store in the token), the secret (a string used to sign the token), and the options (an object that can contain various properties, such as expiresIn, which defines when the token expires).
The jwt.verify() function verifies a JWT. It takes two arguments: the token and the secret. If the token is valid, it returns the payload. If not valid, it throws an error.
In summary, authentication with JWT in NodeJS is a simple and effective process that can significantly improve the security of your APIs. With JWT, you can ensure that only authorized users have access to certain resources, making your application more secure and reliable.