One thing almost every developer can relate to is implementing authentication before building the actual features.
In most applications, many endpoints need to be secured so that only authenticated users can access them. Because of this, authentication is usually one of the first things worth setting up before moving on to the rest of the application.
Choosing an Authentication Method
authentication methods I was familiar with were password-based authentication and OAuth.
Later, I learned that there are other approaches as well, such as magic links and OTP-based authentication.
I decided to go with password-based authentication because I wanted to understand the decisions and problems involved in building authentication myself instead of relying entirely on an external authentication provider.
Password-Based Authentication
In password-based authentication, we store a user's email (or another unique identifier) along with their password.
However, we should never store the actual password in the database. Instead, the password needs to be hashed using a suitable password-hashing algorithm.
There are a couple of important things to consider:
- Store a hashed password, never the plain-text password.
- Verify the user's email or phone number when the application requires account verification.
Registering a User Isn't Enough
Now suppose we stop after registering the user and storing their credentials.
When the user tries to access a feature that is only available to authenticated users, how does the server know that the user has already logged in?
We obviously don't want users to enter their email and password on every single request. That would be a terrible user experience.
This is where sessions and tokens come into the picture.
After a successful login, the application can establish a session for the user. The client can then use the resulting authentication credentials when making subsequent requests, allowing the server to identify and authenticate the user without asking for their password every time.
I'll discuss how sessions, access tokens, and refresh tokens work in the next part.
Learnings
- Create auth endpoints before any feature as it acts as foundation.
- Always hash passwords and verify user.
Top comments (0)