What is Authentication?
StockAPI uses JWT (JSON Web Token) based authentication to secure API endpoints and ensure that only authorized users can access protected resources. Authentication is required for most operations involving products and orders.Why Authentication is Needed
StockAPI is designed for exclusive use by sellers (vendedores) in a small market. Authentication ensures that:- Only authorized personnel can create, modify, or delete products
- Order creation and management is restricted to authenticated users
- Each action can be traced back to a specific user
- Sensitive business data is protected from unauthorized access
The
/products GET endpoint (listing all products) is the only public endpoint that doesn’t require authentication. All other product and order operations require a valid JWT token.Authentication Flow
The authentication flow in StockAPI follows these steps:User Creation
Users are created manually by administrators using the
createUserScript.js utility. Passwords are securely hashed using bcryptjs before being stored in the database.Token Generation
If credentials are valid, the API generates and returns a JWT token that expires in 4 hours.
Authenticated Requests
The client includes the token in the
Authorization header for all subsequent requests to protected endpoints.Security Features
Password Hashing
All passwords are hashed using bcryptjs with a salt factor of 10 before storage
JWT Signing
Tokens are signed with a secret key stored in environment variables
Token Expiration
Tokens automatically expire after 4 hours to limit exposure
Role-Based Access
User roles determine what actions can be performed in the system
Protected Endpoints
The following endpoints require authentication:Products
POST /products- Create a new productGET /products/:id- Get a specific productGET /search- Search for productsPUT /products/:id- Update a productDELETE /products/:id- Delete a product
Orders
POST /orders- Create a new orderGET /orders- Get all ordersDELETE /orders/:id- Delete an order
Next Steps
JWT Tokens
Learn how to obtain and use JWT tokens
User Roles
Understand role-based access control