If you're looking to enhance security, consider utilizing either JWT
tokens or Session Cookies
.
Here's the algorithm:
- User navigates to the /login page.
- User inputs their user id and password.
- You initiate a fetch or Axios request to your server's
POST API
route.
axios(`/<api_route_here>`,{
method: "POST",
headers: {
Authorization: `Basic ${btoa(`${username}:${password}`)}`
}
})
In the code snippet above, we encode the username and password using base64 before sending them back to the server via the Authorization header with format username:password
.
Note: It's crucial to ensure that an HTTPS connection is being used.
- On the server side, decode the Authorization value from the header. Then, generate a hash of the password with the username serving as its salt. Subsequently, query your database to check if the generated hash matches the user's password hash.
The hashing process is implemented to safeguard against exposing passwords in case of a potential database breach. Naturally, store user passwords in the database using the same hashing technique.
If the search in the database yields a positive result, respond with a 200 status code; otherwise, return a 401.
Upon resolving the Axios promise, inspect the header status code to confirm the success of the sign-in operation.
To avoid repeatedly prompting users for their passwords, employ session cookies. For instance, upon successful authentication in step 4, include a Set-Cookie
header property with a session token value. Save this token in your database. Upon subsequent API calls, verify the existence of the cookie and cross-check the session token with the database. If the cookie isn't present, issue a 401
response.
To mitigate route spamming, implement a captcha feature.