2024-07-28
#security
#auth
#jwt
#oauth
#backend

Web Security: JWT & OAuth 2.0

Authentication mechanisms explained: JWT structure and security best practices, OAuth 2.0 flows, and OpenID Connect.

Authentication vs Authorization

  • Authentication (AuthN): Who are you?
    • Verifying identity (Login, Password, 2FA).
    • Failure: 401 Unauthorized.
  • Authorization (AuthZ): What are you allowed to do?
    • Verifying permissions (Admin, Editor, Viewer).
    • Failure: 403 Forbidden.

JWT (JSON Web Tokens)

A compact, URL-safe means of representing claims to be transferred between two parties. Stateless Authentication: The server doesn't need to store session data. The token is the proof.

Structure (Header.Payload.Signature)

  1. Header: Algorithm and Type. {"alg": "HS256", "typ": "JWT"}
  2. Payload (Claims): Data (User ID, Role, Expiration). NOT ENCRYPTED (Base64 encoded only). {"sub": "123", "role": "admin", "iat": 1516239022}
  3. Signature: Verifies integrity. HMACSHA256(base64(header) + "." + base64(payload), SECRET_KEY)

Pros & Cons

  • Pros:
    • Scalable: Good for Microservices (Authentication Service issues token, other services just verify signature).
    • SSO: Easy to implement Single Sign-On.
  • Cons:
    • Revocation: Hard to ban a user instantly (token is valid until expiry).
    • Size: larger than session cookies.

Security Best Practices

  1. Never store sensitive data (passwords) in Payload.
  2. Short Lifespan: Access Tokens should live short (e.g., 15 mins).
  3. Refresh Tokens: Use long-lived Refresh Tokens to get new Access Tokens.
  4. HTTPS: Always transmit over HTTPS to prevent interception.

OAuth 2.0 (Open Authorization)

A standard for delegated authorization. Analogy: Giving a hotel valet your "Valet Key" (Access Token) allows them to park your car (Resource), but not open the trunk or glovebox (Scope).

Roles

  1. Resource Owner: The User.
  2. Client: The App (e.g., Spotify).
  3. Authorization Server: The Identity Provider (e.g., Facebook).
  4. Resource Server: The API holding data (e.g., Facebook API).

The Flow (Authorization Code)

  1. User clicks "Login with Facebook".
  2. User is redirected to Facebook.
  3. User logs in and Consents to scopes (e.g., "Read Friends List").
  4. Facebook redirects back to Spotify with a temporary Code.
  5. Spotify exchanges the Code + Client Secret for an Access Token.
  6. Spotify uses Access Token to fetch data.

OIDC (OpenID Connect)

A layer on top of OAuth 2.0 for Authentication.

  • OAuth 2.0 is for Authorization (Access).
  • OIDC adds an ID Token (JWT) to identifying Who the user is.

Connected Thoughts

Egor Zdioruc | Lead Full Stack Developer | Laravel & AI Solutions