What precautions should I take when setting up my login routes to ensure security?

I am working on developing a login and registration system for a website project, but I'm unsure about the best way to safely implement the routes/logic for it. Currently, in my client-side code, I make fetch requests to either the login or register route, where I handle the logic and then send back a manipulated JSON object based on whether an error occurred. I've also included CORS and Header (Origin and Referrer headers) authorization middleware in my POST routes to prevent external scripts from mass producing users or attempting brute force attacks. Are there alternative, more secure methods for handling this process?

Answer №1

If you're looking to enhance security, consider utilizing either JWT tokens or Session Cookies. Here's the algorithm:

  1. User navigates to the /login page.
  2. User inputs their user id and password.
  3. 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.

  1. 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.

  1. If the search in the database yields a positive result, respond with a 200 status code; otherwise, return a 401.

  2. 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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

Is there a way to prevent advertisements from appearing in npm?

As I execute various npm commands, my console gets bombarded with ads promoting different projects and individuals. While I enjoy contributing to open source projects, I believe the console output of a tool should not be used for advertising. Thank you fo ...

How can I retrieve the path to a specific subnode using Javascript/JSON?

What is the best way to obtain a JSON path that leads to a specific child node within an object? For example: var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } ...

The switch case functionality refuses to change when I interact with the user interface

Can someone please help me troubleshoot? I'm not receiving any errors in the Chrome console. HTML <div class="wrapper"> <i id="repeat" class="fas fa-stop-circle"></i> </div> Javascript const wrap ...

The functionality of toLowerCase localeCompare is restricted in NuxtJs VueJs Framework

Encountered a peculiar issue in NuxtJs (VueJs Framework). I previously had code that successfully displayed my stores in alphabetical order with a search filter. When I tried to replicate the same functionality for categories, everything seemed to be work ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

"Quotes are essential in Javastript syntax for specifying string values

I need to implement a JavaScript syntax to generate unique URLs for each image. The Robohash website provides random robot images based on different URL endings. I tried the code below, but it seems like ${props.id} is being interpreted as part of the UR ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

Unable to retrieve information from a child component in React

So, this component acts as the main container class TaskList extends React.Component { state = { task: '', } handleTaskClick = () => { taskArray.push({id: idCount, text: this.state.task, completed: false}) idCount++ this. ...

What's a way to pass a PHP variable directly to Javascript without using AJAX?

In my setup, I've implemented a JavaScript code that validates and sends the 'artwork' file to a PHP script on my server. This PHP script also performs its own checks for redundancy before writing the file to /uploads directory. The challen ...

React Login Redirect

I am struggling to implement a redirect in my React project login. Despite researching online and finding solutions using routers, I have been unsuccessful in adding it to my code correctly. Here is my code - how can I effectively implement the router? Ap ...

Building a basic music player with the <audio> element and JavaScript / jQuery

I am new to Javascript and jQuery, and this is my first time posting a question here. I have been trying to create custom functions for the HTML5 audio tag by following tutorials online. Despite my efforts, I cannot seem to get it working. Although I can m ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

The function is missing from the object, leading to a script error with jQuery

When using different versions of jQuery, I encountered some issues with saving changes in my application. Initially, with jquery-1.4.4.min.js, everything worked except for the save function due to an error I made. However, when switching to jquery-1.7.1.mi ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

What is the best way to fill out a mandatory text field within the text area?

I am currently facing a challenge with making the comment field mandatory in my PHP application. Despite my lack of expertise, I have been unsuccessful in finding a solution so far. Below is an example code snippet where PHP generates the comment field. Du ...

Incorporate extra HTTP headers using ExpressJS

I am currently using Express.JS to serve a few static pages. The setup process is straightforward: var app = express(); app.configure(function(){ app.use(express.static(path.join(application_root, "StaticPages"))); app.use(express.errorHandler({ dump ...

Using special symbols in HTML5 data attributes

Is it feasible to locate all DOM elements using jQuery with wildcard characters in the attribute name? Take into consideration the following HTML code: <input id="val1" type="text" data-validate-required data-validate-minlength ...

To combine arrays A and B within a React useState object, simply pass them as arguments when initializing the state

Currently, I am working on integrating infinite scroll functionality in React, where I need to fetch data from a backend API for loading content on the next page. The challenge I'm facing is that my state is set as an object using useState, and I need ...

Encountering a blank page issue with react-router-dom v6 Routes

I am attempting to route a page to the root, but it keeps showing up as a blank page regardless of which JavaScript file I use. It seems like React Router DOM has been updated and no longer uses Switch. I haven't used React since last year, so I' ...