Skip to main content

API Authentication

In the previous lessons, we built APIs that anyone could call. But in the real world, you don't want strangers deleting your data! Authentication (AuthN) is how the server verifies that a request is coming from a valid user.

🧐 Authentication vs. Authorization

These two sound similar, but they are very different. At CodeHarborHub, we use the "Office Building" analogy:

  • Authentication (AuthN): Showing your ID card at the gate to enter the building. (Who are you?)
  • Authorization (AuthZ): Your ID card only lets you into the 4th floor, not the CEO's office. (What are you allowed to do?)

Common Auth Methods

Modern APIs usually use one of these three methods to keep things secure:

Simple & Fast

The server gives the client a long, secret string (the Key). The client sends this key in the header of every request.

  • Best For: Public APIs (like Google Maps or Weather APIs).
  • Risk: If someone steals your key, they can act as you.

The Token-Based Workflow (JWT)

This is the most common flow you will build as a Backend Developer:

Best Practices for API Security

  1. Always use HTTPS: Never send passwords or tokens over http. They can be easily stolen.
  2. Use the Authorization Header: Don't put tokens in the URL. Use the standard header: Authorization: Bearer <your_token_here>
  3. Set Expiration: Tokens should not last forever. If a token is stolen, it should expire in a few hours.
  4. Don't Store Secrets in Frontend: Never hardcode your API keys in your React or HTML code. Use .env files.

Summary Checklist

  • I understand that Authentication proves identity.
  • I know the difference between Authentication and Authorization.
  • I understand the JWT "Boarding Pass" workflow.
  • I know that sensitive data must always be sent over HTTPS.
Security Warning

Never, ever commit your API keys or Secrets to GitHub! If you do, hackers can find them in seconds. Always use a .gitignore file to hide your environment variables.