Introduction: Securing User Login with JWT

Welcome back! In the previous lesson, you built a secure registration system that hashed passwords before saving them. Now it’s time to let users log in and access protected areas of your API.

But how do we remember users once they log in? That’s where JWT (JSON Web Token) comes in.

  • When a user logs in successfully, the server issues a signed JWT.
  • The client includes this token in the Authorization header of future requests.
  • The server verifies the token to confirm the user’s identity and role.

By the end of this lesson, you’ll have:

  • A login endpoint that validates credentials.
  • A system that issues JWTs for authenticated users.
  • A way for clients to access protected routes using those tokens.
How bcrypt Verifies Passwords

At registration time, you hashed the user’s password with bcrypt. Now during login, bcrypt needs to check whether the plain-text password the user entered matches the stored hash.

Here’s the interesting part: bcrypt hashes aren’t deterministic in the way you might expect. Even if two users both use "password123", their stored hashes will look completely different. That’s because each hash contains:

  • The salt (a random string generated when hashing).
  • The cost factor (how many rounds of hashing).
  • The final hash itself.

When verifying:

  1. bcrypt extracts the salt and cost factor from the stored hash string.
  2. It applies the same algorithm to the candidate password.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal