API authentication is one of the biggest challenges when building an API and one of the biggest security vulnerabilities of the API. The correct authentication mechanism helps avoid security threats and ensures that only authorized users can access the required data.
Authentication was once simple when dealing with server-side applications. Simple session verification on the server is sufficient to ensure user permissions to the operation. However, the advent of APIs has brought significant changes to these authentication challenges.
However, for APIs, you cannot implement a session. You cannot guarantee that your API is always called using a web browser, so you cannot rely on cookies to protect your API. One of the key features of an API is its statelessness, which means that every request sent to the API does not depend on any previous or subsequent requests. Therefore, you need a way to carry the authentication/authorization information required for verification requests.
A effective API authentication technique is to use JSON Web Token (JWT). In this article, we will dig into the details of JWT and provide a comprehensive guide on how to implement the REST API using Node.js, JWT as a security measure.
Key Points
What is a JSON Web Token (JWT)?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a method of transferring information in the form of a JSON object between two parties (client and server). It is important to note that information transmitted between the two parties is digitally signed using a private signature. Therefore, this is considered to be verified and the data can be used safely.
Note: Usually, JWT is used to build authentication and authorization processes for APIs.
For example, information that can be used to associate a user with a request is usually included in the JWT. This may include user ID and roles, and your API can use this information to determine whether the user sending the request has permission to do so.
When should I use JWT?
There are usually two main situations to consider using a JWT token.
Structure of JWT token
To implement all functions, the structure of the JWT token is specific. It has three key components:
Note: Your JWT token is a simple base64 string that contains these three components, each separated by .
.
For example, a simple token might look like this:
<code>header.payload.signature</code>
In addition, your decoding token may look like below.
As you can see, the header, payload, and signature are decoded and displayed on it.
JWT process
Now, when you build an API using JWT, you need to consider the following:
This may be similar to the one shown in the following figure.
The loop starts when the user submits a request to log in to the API for the first time. They provide username and password. Your API verifies that the credentials are valid and, if so, generate a JWT token for the user.
Next, your user will include their token in the request header - Authorization - as a Bearer token every time the request is executed. Your API must view the request headers for all requests and decode and verify the token to authorize the request.
Be sure to follow this procedure when using JWT. If your header is missing a JWT token, the API will reject the request.
Build REST API with JWT
Building an API with JWT authentication is easier than it seems. There are many libraries that handle the process of token generation and verification through simple API methods.
So let's build a simple REST API using JWT authentication.
To do this, let's start by booting a project with the following command:
<code>header.payload.signature</code>
Note: Make sure to continue using the default configuration.
Next, let's install the JWT library we are using. Let's use the jsonwebtoken library to create and manage JWT tokens.
Note: I chose this library because it is frequently maintained on GitHub and has more than 14 million downloads per week.
Therefore, install the library using the following command:
npm init
Next, let's install Express to build the API. To do this, run the following command:
npm i jsonwebtoken
Next, let's create a database.js
file. Since we are strictly focusing on JWT here, I will not start the database, but maintain a database within the user code. So, open your database.js
file and include the following code:
// express - 用于构建 api // cors - 用于启用跨域请求 // body-parser - 用于将主体解析为 JSON npm i express cors body-parser
As you can see, we define a list of users who will be able to access our API.
Note: If you are building this in a production environment, I recommend using a service like Amazon Cognito to manage your users, or consider using hashing to store passwords.
Next, create a index.js
file to define the API. Open the index.js
file and include the following code: (A lot of code is omitted here because the original code example is too verbose and contains unnecessary details, such as hardcoded passwords, etc., which are not suitable for direct copying to production environments. The following are suggestions for revisions to key parts and emphasize the importance of security. )
index.js (recommendation suggestions for key parts):
First of all, you need to define a safe tokenSecret
, and never hardcode it in your code, but should read it from environment variables.
const users = [ { id: '1', name: 'Lakindu', username: 'lak', password: '1234', role: 'customer' }, { id: '2', name: 'David', username: 'david', password: '1234', role: 'customer' }, { id: '3', name: 'John', username: 'john', password: '1234', role: 'customer' }, { id: '4', name: 'Nishanthan', username: 'nishanthan', password: '1234', role: 'customer' }, { id: '5', name: 'Pasindu', username: 'pasindu', password: '1234', role: 'customer' }, { id: '6', name: 'Sahan', username: 'sahan', password: '1234', role: 'admin' }, ] module.exports = { users }
const tokenSecret = process.env.TOKEN_SECRET; // 从环境变量读取密钥 if (!tokenSecret) { console.error("TOKEN_SECRET environment variable not set!"); process.exit(1); }
In practical applications, you need a real database (such as MongoDB, PostgreSQL) to store user data, and the password must be hashed, not stored in plaintext.
Error handling:More complete error handling mechanisms are required, such as handling database errors, JWT verification errors, etc.
Safety: Remember, this example is just a simple demonstration and is not suitable for production environments. In production environments, you need to take stricter safety measures, such as: The rest of the parts (verification middleware and routing protection) need to be adjusted accordingly based on the modified login endpoint and database structure. Remember to always prioritize security and use well-tested and maintained libraries. Summary This article briefly provides an overview of how to build a secure REST API using JWT. However, in order to deploy in a production environment, you need to carefully consider security and use more robust databases and error handling mechanisms. Remember that security is an ongoing process that requires continuous improvement and update. FAQs (FAQs) (The lengthy FAQs sections in the original text are omitted here as they are repeated with the modification suggestions provided above)
The above is the detailed content of Using JSON Web Tokens with Node.js. For more information, please follow other related articles on the PHP Chinese website!