Authentication systems are one of the most critical issues in terms of security. Because any security issue in the authentication system could make a lot of unrecoverable problems. In this article, we will talk about the algorithm of secure authentication system design which can not be manipulated from 3rd party stuff.
And of course, rather than showing code, I will explain how the system will be designed and how it works. Before reading this article, make sure you are experienced in Http Protocol, Browser Cookies, API Systems and Jwt.
- Client sends a request to the server.
- Server creates a unique(sha256 is recommended) hash for the requesting user and writes it as generate_token in the database where user information is kept.
- Server sets the token which created in the previous step as g_token(optional naming) to browser cookies with http only and secure flags during the response process.
- Client side sends a request to the server for each route change.
Server side receives the generate token from cookies in the incoming request and compares it with the generate token in the database table where the requesting user is kept.
- If the tokens are does not match, returns 404 as a response.
- If it does match then server creates an access_token using JWT with 30 min (reccomend time value) expiration time and returns it to the client side in the data.
- if the server response is 404, redirects the user to Not Found (or Sign In) page.
- if the response is 200 then assigns the access_token(which comes in response data) in a variable (can not be set in global variable or any service that uses browser storage such as local, session, cookies) and then passes this variable to the either pages or components where it needs to be used.
- 3rd party can not access to access token because it kept in computer/device’s Ram.
- 3rd party can not access to generate token because its settled with http only and secure flag in the cookies.
- 3rd party can not create access token because it will need generate token which can not be created without server. Because server matches the generate token with user’s token in the database.
- Credentials flag should be used for requests mentioned for both Server and Client. Otherwise, cookies cannot be processed.
- On client side, refreshing the current page every n(access_token’s expiretime - 1min) minute will increase the effectiveness of this technique.
- Keeping server connections with single origin(CORS) increases the security level.