Skip to main content

What are JWT Tokens?

JSON Web Tokens (JWT) are a secure way to transmit information between parties as a JSON object. In StockAPI, JWT tokens are used to authenticate users and maintain secure sessions. A JWT token contains encoded information about the user, including:
  • User ID
  • Username
  • User role
  • Token expiration time

Token Structure

When you successfully log in, StockAPI generates a JWT token with the following payload:
// From authController.js:23-27
const token = jwt.sign(
    { id: user._id, username: user.username, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '4h' }
);
The token includes:
  • id - The user’s unique database ID
  • username - The user’s username
  • role - The user’s role (e.g., “vendedor”, “developer”)
  • Expiration set to 4 hours from generation

Obtaining a Token

To obtain a JWT token, you need to authenticate using the /login endpoint.

Login Request

curl -X POST https://api.stockapi.com/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin2",
    "password": "1234"
  }'

Successful Response

If authentication is successful, you’ll receive a response like this:
{
  "message": "Login exitoso",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY3MzRhYmNkZWYxMjM0NTY3ODkwIiwidXNlcm5hbWUiOiJhZG1pbjIiLCJyb2xlIjoidmVuZGVkb3IiLCJpYXQiOjE3MzE1MDAwMDAsImV4cCI6MTczMTUxNDQwMH0.abc123def456ghi789jkl012mno345pqr678stu901vwx234yz",
  "user": {
    "username": "admin2",
    "role": "vendedor"
  }
}

Error Responses

{
  "message": "Usuario no encontrado"
}
The username provided does not exist in the database.
{
  "message": "Contraseña incorrecta"
}
The password provided is incorrect.
{
  "message": "Error en el login",
  "error": "Error message details"
}
A server error occurred during authentication.

Using Tokens in Requests

Once you have a token, you must include it in the Authorization header of all requests to protected endpoints.

Authorization Header Format

The token must be sent in the following format:
Authorization: Bearer <your-token-here>
Note the space between “Bearer” and the token. The middleware splits the header value on the space character to extract the token.

Example Authenticated Requests

curl -X POST https://api.stockapi.com/api/products \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Coca Cola 2L",
    "price": 250,
    "stock": 50,
    "category": "Bebidas"
  }'

Token Verification Process

When you send a request with a token, the verifyToken middleware validates it:
// From jwtMiddleware.js:8-25
function verifyToken(req, res, next) {
    // El token normalmente se manda en headers: Authorization: Bearer <token>
    const authHeader = req.headers['authorization'];

    if (!authHeader) return res.status(401).json({ message: 'No se proporcionó token' });

    const token = authHeader.split(' ')[1]; // 'Bearer <token>'

    if (!token) return res.status(401).json({ message: 'Token inválido' });

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded; // guardamos info del usuario en la request
        next(); // seguimos al controlador
    } catch (err) {
        res.status(403).json({ message: 'Token expirado o inválido' });
    }
}
The middleware:
  1. Checks if the Authorization header is present
  2. Extracts the token from the “Bearer” format
  3. Verifies the token signature and expiration
  4. Decodes the token and attaches user information to the request
  5. Allows the request to proceed or returns an error

Token Expiration

Tokens expire 4 hours after generation. After expiration, you must log in again to obtain a new token.

Handling Expired Tokens

When a token expires, requests will fail with a 403 status:
{
  "message": "Token expirado o inválido"
}
When you receive this error:
  1. Make a new login request with valid credentials
  2. Obtain a new token
  3. Update your application’s stored token
  4. Retry the original request

Best Practices

Store Securely

Store tokens securely in your application (e.g., httpOnly cookies, secure storage)

Handle Expiration

Implement automatic token refresh logic before the 4-hour expiration

Don't Share Tokens

Never share tokens between users or expose them in client-side code

Clear on Logout

Remove stored tokens when users log out of your application

Common Authentication Errors

Status CodeMessageCauseSolution
401No se proporcionó tokenMissing Authorization headerInclude the Authorization header in your request
401Token inválidoMalformed token or missing Bearer prefixCheck the Authorization header format
403Token expirado o inválidoToken has expired or signature is invalidLog in again to obtain a new token
401Usuario no encontradoInvalid username during loginVerify the username is correct
401Contraseña incorrectaInvalid password during loginVerify the password is correct

Next Steps

User Roles

Learn about role-based access control

Products API

Start making authenticated requests to manage products