Video summary

Golang Microservice Full Course #05 - JWT Authentication & Bcrypt

Main summary

Key takeaways

Technology

Tech focus of the course (JWT auth + password hashing in a Go microservice)

  • Adds authentication to an existing centralized/structured logging setup.
  • Uses bcrypt to hash passwords (previous version did not hash).
  • Uses JWT (with HS256) to issue access tokens and validate them via middleware.
  • Introduces:
    • a login endpoint
    • a protected route (/users/me) that requires a valid JWT.

Dependency / package setup

  • Adds bcrypt package: golang.org/x/crypto/bcrypt
  • Adds a JWT library: github.com/.../golang-jwt/...
    • The course references the “newest” JWT version and installs golang-jwt.

Password hashing (service layer)

  • Implements password hashing using bcrypt:
    • bcrypt.GenerateFromPassword(passwordBytes, bcrypt.DefaultCost)
  • On login, verifies passwords using bcrypt comparison:
    • bcrypt.CompareHashAndPassword(storedHash, providedPassword)

JWT helper design

  • Creates a new folder/package (mentioned as owls) for JWT-related code.
  • Defines a JWT claims struct including:
    • UserID (string)
    • Email (string)
    • standard JWT registered claims (duration, numeric date, etc.)
  • JWT secret handling:
    • Notes that hardcoding secrets is insecure.
    • Reads the JWT secret from the environment (s.env / .env).
    • Includes logic for local dev vs. empty/invalid in production.
  • Token generation:
    • Claims are created using user ID + email + duration.
    • Uses HS256 signing.
    • Token validity:
      • Access token: 15 minutes
      • Refresh token: 7 days (mentioned as 7 * days)
  • Token validation:
    • A ValidateToken function parses JWT and validates it with the secret key.
    • Returns validated claims or an “invalid/expired token” error.

Login API (request/response + service logic)

Request model

  • email (required)
  • password (required)

Response model

  • access_token
  • refresh_token

Service login flow

  1. Lookup user by email.
  2. If not found: return 401 Unauthorized with a generic message.
  3. Verify password hash via bcrypt compare.
  4. If wrong password: return 401 Unauthorized with a generic message emphasizing:
    • not revealing whether the email or password was wrong (“wrong email or password”).
  5. Generate access token (user ID + email, 15 min).
  6. Generate refresh token (user ID + email, 7 days).
  7. Return both tokens.

Handler: login endpoint

  • Gin handler binds JSON request body.
  • On binding error: returns 400 Bad Request with “invalid input”.
  • Calls service login:
    • On service error: returns the appropriate HTTP error response.
    • On success: returns JSON like:
      • success: true
      • data: { access_token, refresh_token }

JWT auth middleware (protected routes)

  • Adds an auth middleware for protected endpoints.
  • Middleware behavior:
    • Reads Authorization header.
    • Enforces format: must be Bearer <token>.
    • If missing/malformed: 401 Unauthorized
    • Validates token using ValidateToken.
    • On success, stores claims in Gin context:
      • user ID
      • email
  • Applied via route grouping (e.g., protected.Use(auth)).

Protected endpoint (/users/me)

  • Creates a handler that returns the current user profile based on the user ID from JWT claims (from context).
  • Mentions calling a service method like:
    • GetProfile(ctx, userID)
  • Returns JSON containing a user object/data.

Testing notes (Postman)

  • Video tests with Postman:
    • Sets environment variable: host = http://localhost:8080
    • Calls registration and then login.
  • Observations:
    • Ensures password is stored hashed (not plaintext).
    • Invalid credentials should return 401 with “wrong email or password”.
    • If JSON binding/middleware handling isn’t returning correctly, incorrect responses may occur—video mentions fixing global error handling / returning from binding error cases.

Git/branch workflow

  • Updates from master and implements a feature branch (referenced as “feature 05”).
  • Runs go mod tidy (to clean modules).
  • Commits and pushes to origin, creates PR, merges, then checks out/updates master.

Main speakers / sources

  • Primary speaker: the instructor (onscreen/course author; repeatedly says “we” and gives step-by-step coding guidance).
  • Primary technical sources used by the code:
    • golang.org/x/crypto/bcrypt
    • JWT library referenced as golang-jwt (GitHub module)
  • Client used for testing: Postman

Rate this summary

Your feedback will help improve summaries.

Improve this summary

Reprocess with a stronger model when the summary feels incomplete or inaccurate.

Pro

Translate summary in another language

Pro

Ask questions to this video

Chat for follow-up questions, clarifications, and source-backed answers.

Coming soon

Share this summary

Original video