Part 4: Authentication and Authorization

The $50,000 Security Lesson

In my second year as a developer, I built an admin dashboard API. I implemented authentication—users had to log in with email/password. I felt secure.

Until our security audit revealed: any authenticated user could access admin endpoints. A regular customer could delete products, modify orders, view all user data. We had authentication (who you are) but no authorization (what you can do).

We were lucky—caught before production. That audit taught me: authentication gets you in the door, authorization decides which rooms you can enter.

This article covers both, using patterns from my production microservices.

Authentication vs Authorization

Authentication: Verifying identity

  • "Who are you?"

  • Login with email/password

  • Returns access token

Authorization: Verifying permissions

  • "What can you do?"

  • Check user role/permissions

  • Allow or deny access

Real example:

JWT (JSON Web Tokens)

JWT is the standard for stateless authentication in REST APIs.

JWT Structure

Header: Algorithm and token type

Payload: User data (claims)

Signature: Ensures integrity

JWT Service Implementation

Authentication Service

Authentication Controller

Authentication Middleware

Authorization Middleware

Protected Routes

Refresh Tokens

For production, implement refresh tokens to avoid storing long-lived JWTs.

API Usage Examples

Key Takeaways

  1. Authentication verifies identity, Authorization verifies permissions

  2. JWT provides stateless authentication

  3. Never store passwords in plain text - always hash with bcrypt

  4. Short-lived access tokens (15min) with long-lived refresh tokens (30 days)

  5. Role-based (RBAC) and permission-based authorization

  6. Ownership checks ensure users access only their resources

  7. 401 Unauthorized for authentication failures

  8. 403 Forbidden for authorization failures

  9. Revoke refresh tokens on logout

  10. Validate tokens on every protected endpoint

Next in series: Error Handling and Validation—building robust APIs that handle failures gracefully.


Security isn't optional. Implement authentication and authorization from day one.

Last updated