Skip to main content

Overview

ServITech uses JWT (JSON Web Tokens) for stateless authentication. Tokens are generated upon successful login and must be included in the Authorization header for protected endpoints.

Token Generation

When you successfully authenticate via the /auth/login endpoint, the API returns:
{
  "success": true,
  "message": "User logged in successfully",
  "data": {
    "user": {
      "id": 1,
      "role": "USER",
      "name": "John Doe",
      "email": "[email protected]",
      "phone": "+1234567890"
    },
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "expires_in": 3600
  }
}
token
string
required
The JWT access token for authentication
expires_in
integer
required
Token lifetime in seconds (default: 3600 seconds = 1 hour)

Token Structure

JWT tokens consist of three parts separated by dots:
header.payload.signature
Contains token type and signing algorithm:
{
  "typ": "JWT",
  "alg": "HS256"
}

Payload

Contains user claims and metadata:
{
  "iss": "https://api.servitech.com",
  "iat": 1709913600,
  "exp": 1709917200,
  "nbf": 1709913600,
  "jti": "a7b3c9d1e5f2",
  "sub": 1,
  "prv": "87e0af1e..."
}
iss
string
Issuer - The API that issued the token
iat
integer
Issued At - Unix timestamp when token was created
exp
integer
Expiration - Unix timestamp when token expires
nbf
integer
Not Before - Token is not valid before this timestamp
sub
integer
Subject - The user ID the token belongs to
jti
string
JWT ID - Unique identifier for this token

Signature

Created using the header, payload, and secret key defined in JWT_SECRET environment variable.

Token Configuration

Configuration is managed in config/jwt.php:
SettingEnvironment VariableDefaultDescription
Time to Live (TTL)JWT_TTL60 minutesToken expiration time
Refresh TTLJWT_REFRESH_TTL20160 minutes (2 weeks)Refresh window after expiration
AlgorithmJWT_ALGOHS256Signing algorithm
Blacklist EnabledJWT_BLACKLIST_ENABLEDtrueEnable token blacklisting on logout
LeewayJWT_LEEWAY0 secondsClock skew tolerance
SecretJWT_SECRET-Secret key for signing (required)
Never expose your JWT_SECRET in client-side code or public repositories. Keep it secure in your .env file.

Using Tokens

Include the JWT token in the Authorization header with the Bearer scheme:
curl -X GET "https://api.servitech.com/user/profile" \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." \
  -H "Accept: application/json"

Token Storage

Web Applications

For web applications, store tokens securely: Recommended approaches:
  1. HttpOnly Cookies (most secure)
    • Not accessible via JavaScript
    • Automatic inclusion in requests
    • Protected from XSS attacks
  2. Memory/State Management (e.g., Redux, Vuex)
    • Token lost on page refresh
    • Requires re-authentication
    • Safe from XSS if properly implemented
Not recommended:
  • ❌ localStorage (vulnerable to XSS attacks)
  • ❌ sessionStorage (vulnerable to XSS attacks)

Mobile Applications

For mobile apps:
  • iOS: Use Keychain Services
  • Android: Use EncryptedSharedPreferences
  • React Native: Use react-native-keychain or expo-secure-store

Token Expiration

Tokens expire after the configured TTL (default: 60 minutes).

Handling Expired Tokens

When a token expires, the API returns:
{
  "success": false,
  "message": "Token has expired",
  "errors": {}
}
HTTP Status: 401 Unauthorized

Token Refresh

While the current implementation doesn’t expose a dedicated refresh endpoint, you can:
  1. Re-authenticate - Use the /auth/login endpoint to get a new token
  2. Implement refresh logic - Request a new token before expiration
The refresh window (JWT_REFRESH_TTL) is 2 weeks by default. This setting is primarily for internal package behavior.

Token Blacklisting

When a user logs out via /auth/logout, the token is added to a blacklist:
  • Blacklist Enabled: JWT_BLACKLIST_ENABLED=true (default)
  • Grace Period: JWT_BLACKLIST_GRACE_PERIOD=0 seconds (default)
Blacklisted tokens cannot be used for authentication, even if they haven’t expired.

Database Storage

Blacklisted tokens are stored in the database (via the configured storage provider) and checked on each authenticated request.

Security Best Practices

Never transmit tokens over unencrypted HTTP connections. Always use HTTPS in production to prevent token interception.
Use reasonable TTL values (30-60 minutes recommended). Shorter lifetimes reduce the window for token abuse.
The API automatically validates tokens using the auth:api middleware. Never skip this validation.
Periodically rotate your JWT_SECRET and invalidate all existing tokens by requiring re-authentication.
Log authentication events and monitor for unusual patterns (e.g., tokens used from multiple IPs).

Error Handling

Common JWT-related errors:
ErrorHTTP StatusDescriptionSolution
Token has expired401Token TTL exceededRe-authenticate to get a new token
Token invalid401Malformed or tampered tokenVerify token format and signature
Token not found401No Authorization headerInclude token in request header
Token blacklisted401Token was invalidated via logoutRe-authenticate to get a new token

Login

Get a JWT token by logging in

Logout

Invalidate your token

Build docs developers (and LLMs) love