Content Overview
This article expands on a previous tutorial covering basic CRUD API creation with Express.js, focusing on crucial security aspects: validation, authentication, and authorization. We'll build upon the previous example, so familiarity with that material is recommended. The complete project is available on GitHub (link provided below).
Key Concepts
Validation: Ensuring user-provided data conforms to predefined rules and standards. This is paramount for security, preventing vulnerabilities like SQL injection. Several resources highlight the importance of robust validation (links provided below).
Authentication: Verifying a user's identity. This typically involves checking credentials (e.g., username/email and password) against stored records.
Authorization: Determining what actions a user is permitted to perform. This controls access to resources based on user roles and permissions.
Implementing Validation
We'll create validation functions for name
, amount
, and date
fields:
name
: String, non-empty, 10-255 characters.amount
: Number or numeric string, positive, non-empty.date
: String, optional (defaults to current date if omitted), YYYY-MM-DD format.These functions (located in validations.js
) utilize type checking and basic format validation. More comprehensive validation (e.g., date range checks) could be added.
<code class="language-javascript">// validations.js (excerpt) const isString = (arg) => typeof arg === "string"; const isNumber = (arg) => !isNaN(Number(arg)); function isValidName(name) { /* ... */ } function isValidAmount(amount) { /* ... */ } function isValidDate(date) { /* ... */ } module.exports = { isValidName, isValidAmount, isValidDate };</code>
Adding Authentication and Authorization
For demonstration, we'll use in-memory data storage (an array of objects) for users and expenses. This is not suitable for production.
The data.js
file stores user and expense data:
<code class="language-javascript">// data.js (excerpt) let users = [ { id: "...", email: "...", password: "..." }, //Example User // ...more users ]; let expenditures = [ { id: "...", userId: "...", name: "...", amount: ..., date: "..." }, //Example Expense // ...more expenses ]; module.exports = { expenditures, users };</code>
Signup Endpoint (/users/signup
)
This endpoint creates new users. It validates email and password, checks for email duplicates, generates a UUID, and (for this demo only) stores the raw password. A base64 encoded authentication token (email:UUID) is returned. Password hashing is omitted for simplicity but is crucial in a production environment.
Login Endpoint (/users/login
)
This endpoint authenticates existing users. It validates credentials and returns a base64 encoded authentication token if successful.
Protected Endpoints
To protect endpoints (e.g., /expenditures
), we'll require an authentication token in the request headers (Authorization
header). The token is decoded, the user is verified, and only the user's own data is returned.
<code class="language-javascript">// validations.js (excerpt) const isString = (arg) => typeof arg === "string"; const isNumber = (arg) => !isNaN(Number(arg)); function isValidName(name) { /* ... */ } function isValidAmount(amount) { /* ... */ } function isValidDate(date) { /* ... */ } module.exports = { isValidName, isValidAmount, isValidDate };</code>
Conclusion
This article provided a basic introduction to validation, authentication, and authorization in a Node.js/Express.js API. Remember that the security measures demonstrated here are simplified for educational purposes and should not be used in production systems. Production-ready applications require robust password hashing, secure token management (JWTs are recommended), and database integration.
Resources
(Remember to replace the bracketed placeholders with actual links.)
The above is the detailed content of Validation, Authentication and Authorization. For more information, please follow other related articles on the PHP Chinese website!