π How JWT Authentication Works Behind the Scenes
Whenever you log in to a website using your username and password, thereβs a secure process going on in the background to make sure your data stays safe. Letβs break it down step by step in simple terms:
1. User Sends Login Request
You enter your username and password and hit the login button. This info is sent from your browser to the server through a secure request.
2. Server Verifies Credentials
The server checks the username and password by comparing them with the records stored in its database.
- β If the credentials match, then the login is successful.
- β If they donβt, youβll get an error like βInvalid credentials.β
3. JWT Token is Generated
Once the credentials are verified, the server creates a JWT (JSON Web Token). This token is a small piece of data that confirms your identity.
- The server signs the token using a private key.
- This step uses cryptography to ensure the token is secure and canβt be tampered with.
4. Token is Sent to Browser (Stored in Cookies)
After signing, the JWT is sent back to your browser and usually stored in a cookie.
- This cookie is automatically sent with every future request to the server.
5. Accessing Protected Routes
Now suppose you try to access a protected route, like /getProfile.
- The browser sends the JWT token from the cookie along with the request.
- The server receives the token and tries to verify it using the same private key it used to sign it.
6. Token Verification
There are two possible outcomes here:
- β Valid Token: If the token is not expired and hasnβt been modified, the verification passes and you get access to the protected route.
- β Invalid Token: If someone tried to manipulate the token or the expiry time is over, the server rejects it and throws an error.
π§ TL;DR
JWT makes it possible to:
- Log in once β
- Prove your identity using a token π
- Stay authenticated without sending your username/password every time π