Authentication system is very important piece of puzzle in fullstack applications. applications can be built using any language or any framework and under the hood it can use any database but the core concepts of the authentication system will always remain same. In this blog post we will explore those concepts. Before we need to understand some things in the system.
Here a user initiates a web request and then a server responds with a response after executing some business logic
It can be divided into three main parts they are
- Create user/ Signup
- Login User
- Private Pages/ Protected Routes
Create User/ Signup
Logic for new user creation.
- Client sends a web request with data for new account creation. In this example we took a basic example with email, user name and password.
- Server validates the request data with the logic we have written.
- It is not safe to save password in plain text so we need to encrypt it and store it in database. In nodejs we can use in built crypto module to encrypt password
- Send a success message or error message to the client based on our operations
Logic for user login/signin
- Client sends a webrequest with username and password
- Sever finds user by usename in database
- Compare password if there is user
- If everything is correct generate a session token or a cookie and send it in response
Private pages/ Protected routes
Some pages might be private for users so we need to have some middleware functions to keep checking if the user has valid session or not.
Middleware functions are the functions that execute between request and response
- Client sends a request with the token we have given when he logged in.
- Our middleware checks if the token is authentic or not. if it is authentic it hands over control to next function or else it returns error
This is basically the overview of a basic authentication system.