What are the best practices for protecting a web application with login and database in the year 2022?

My knowledge of security is outdated and I am looking to update my skills in full stack development. Currently, I am exploring Oauth2, JWT, Next.JS, Auth0, and more, but I am struggling to integrate all these components together. Please bear with me as I make an effort to ask this question :)

Imagine I want to create a web application where users can register for access to a building. They would input their personal information and receive a user-friendly check-in number (e.g. A00001 - Z99999).

o/    ___              
/▌   |App| --POST---> API --> Add User to MySQL, assign number-|
/\    ———  <---------------------Return number--------------------|            
  1. How can I secure the /user POST endpoint to prevent spamming by malicious hackers?

Now, there is a security officer stationed at the entrance of the building with an admin app. They can view all users and approve their entry into the building.

 O/    _________  ---PUT---> API --> Update User                       
/▌    |Admin App| ---GET---> API --> Retrieve All Users -|
/\     —————————  <-------send all users--------|
  1. How can I secure the /user GET endpoint so that only authenticated admins have access to view all users?
  2. How can I secure the /user PUT endpoint so that only authenticated admins can modify user data?
  3. The user should be able to log in but not register. There is only one admin account.

There is no registration process for the admin. Only one admin account with a username and password login. Regular users do not require a GET /user/[id]. However, is it secure if I send them a link with a 32-bit hash and then allow access through a GET /user/[hash] endpoint?

For those willing to assist with code, I'll share a sample along with the question:

// pages/checkin.js
export default function Checkin() {

    const checkin = async (e) => {
        e.preventDefault();
        try {
            await fetch('https://myapi.com/user', {method: "POST", data});
        } catch (err) {
            console.log(err);
        }
    }

    return (
        <div>
            <form onSubmit={checkin}>
                {/* ... */}
            </form>        
        </div>
    )
}
// pages/_app.js
import { UserProvider } from "@auth0/nextjs-auth0";

function MyApp({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}
export default MyApp;
// pages/api/auth/[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();
// pages/userList.js
import { useUser } from '@auth0/nextjs-auth0';

export default function UserList() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  {/*
    * How and where do I fetch the secured users?
    */}

  const ok = async (id) => {
      try {
          /*
           * How to secure the PUT request? 
           */
        await fetch('https://myapi.com', {method: 'PUT', data: {id, ok: true}})
      } catch (err) {
          console.log(err);
      }
  }

  return (
    user && (
      <div>
        {users.map((user) => (
            <div key={user.id}>
                {user.human_numer} - <button onClick={() => ok(user.id)}>OK</button>
            </div>
        ))}
      </div>
    )
  );
}

Answer №1

Here are some security tips from me, although I am not a security expert - just someone who codes web apps frequently:

  • Consider using bcrypt (https://www.npmjs.com/package/bcrypt) for a simple and secure module.
  • If you are working with nodejs (which is likely) and have set up your app with express, consider utilizing the express-ratelimit middleware to help prevent spam.
  • I found securing GET requests to be quite challenging. Given that the internet is inherently open, restricting content access can be tricky. You may choose to:
    • Whitelist only your own IP address (if static) or match it with your user-agent in order to block all other IPs. Keep in mind this could pose challenges if you need to work while travelling.
    • Implement temporary bearer tokens that are valid for one-time use. However, be cautious as if your database holding these tokens or the token generator gets compromised, your entire app could be at risk.
  • If you only require login functionality without registration, simply manually enter the credentials into your database.
  • In my opinion, it's not necessary to connect everything to a single domain. Consider setting up a local or external dashboard to manage user data directly. Once again, restrict access by whitelisting your IP address and blocking others.

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

Having trouble retrieving a remote JSON link from a local HTML file in Google Chrome

Having trouble fetching a JSON from the following link: [https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050]. When accessed through a browser, the JSON is displayed on screen as expected. However, attempting to fetch this link from JavaScrip ...

offspring of offspring in jquery animation remains stationary

I'm experiencing an issue with a jquery animation on containers that are set to 100% width and height. Specifically, the children elements that have position absolute move with the container, but when a child of a child has two instances of position a ...

Looking for a character that includes both lowercase and uppercase letters

Here is the JSON data I have: [ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] var searchBarInput = TextInput.value; var ...

Developing a personalized Avada form auto-scrolling algorithm

Our form, created using the Wordpress - Avada theme, needs an autoscroll feature. As users answer questions, the next question appears below, but this is not immediately visible on mobile devices. To address this, we require autoscroll functionality. The ...

The use of dangerouslySetInnerHTML in a React application is causing issues when trying to include Segment.io tags

Currently, I'm integrating Segment.io into my react/NextJS application. I'm mimicking the pattern established by a previous function that deals with Google Analytics const segmentWriteKey = 'xyz'; export default class CustomDocument ...

Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this: private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) { let firstTime; let secondTi ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

Modify the text of a button using JavaScript without referencing a specific div class

THE ISSUE I'm facing a challenge in changing the text of a button on my website. The <div> I need to target doesn't have a specific class, making it difficult for me to make this edit. While I have some basic understanding of JavaScript, ...

Issue with the Jquery rich text plugin in Internet Explorer causing functionality problems

I have encountered an issue while trying to use a jQuery richtext editor in Internet Explorer. Interestingly, it fails to work in IE but functions properly in Chrome. Here is the code snippet where I call the plugin and it works well in all browsers excep ...

Clicking to center div elements

When clicking on my div elements, they transform into flipcards and expand to a size of 600px by 600px. I want these divs to be centered in the middle of the screen when clicked, and then move back to their original position when clicked again. I've b ...

Is there a live password verification tool available?

Currently, I am conducting some initial research for my school's IT department as a student employee. The students at our institution are required to change their passwords every six months, but many of them struggle with the various password regulati ...

Playing with vue component dependencies

During my attempt to run a unit test, I encountered an error when making an axios call. To handle this error, I successfully mocked the call but faced an issue when trying to utilize an external library dependency (specifically, vue-toasted) to display an ...

How to Retrieve the Following Element in a Table Using Javascript

https://jsfiddle.net/en6jh7pa/1/ I am encountering an issue with accessing the next element, as it is returning null. When I pass "this" as the onclick parameter, I expect to be able to grab the next element using this keyword. However, it seems to be re ...

Introducing the NextAuth Provider module

In the official NextAuth documentation, it is recommended to wrap the component with the Provider as shown below: import { Provider } from "next-auth/client" export default function App({ Component, pageProps }) { return ( <Provider ...

Retrieving a property of an object within an array using JavaScript in AngularJS

Seeking advice on how to calculate the total price of products in an array when working within a callback function. Is there a method similar to myArray.(intheobject).price? Or is there a way to handle callbacks effectively to achieve accurate results? th ...

Utilizing Thymeleaf With JavaScript in Spring Boot: A Comprehensive Guide

Within my Spring Boot project, I am attempting to utilize Thymeleaf for injecting data into a JavaScript file that undergoes preprocessing with babel via WebPack. The Thymeleaf setup is outlined as follows: @Bean public SpringTemplateEngine templateEngine ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

Adding an item to a list using the PATCH method in Angular 7

Can anyone provide guidance on how to implement the PATCH method for manipulating an array within another array? ItemClass: export class ItemClass { constructor(public person: string, public name: string, public quantity: number, public price: number){} ...

Is there a way to automatically collapse all the collapsible elements within the accordion when closing it?

I came across a similar topic on Stack Overflow about closing all children accordions when the parent accordion is closed, which seems to address my issue. Currently, I am using Bootstrap 4 and struggling to modify the code from the other topic to ensure ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...