Securing a web application

Dustin Morris
3 min readNov 16, 2020

My last article I was working on a spinning wheel for random list selection. This is a continuation of that project.

I want my users to be able to make their own lists. In order to do that, I need to allow the users to store data. So a simple spinner wheel has now taken on a fair bit more complexity.

Tasks needed to perform to store a list:

  1. Persistent storage — I chose Azure Cosmos DB with MongoDB. I am using Mongoose as an ODM.
  2. Prevention of attacks —

a. I am using HELMET middleware to automatically set headers on my. responses.

b. CORS middleware for cross-origin requests.

c. VALIDATE for ensuring my users enter appropriate data.

d. XSS to prevent cross site scripting attacks.

e. JSONWEBTOKEN for security and user persistence.

f. DOTENV to process secrets stored in my environment file.

g. BCRYPT for hashing and salting passwords.

Whew! That is a lot just to allow my users to SAFELY store their lists.

Here are a few snippets of what I did to secure their data:

First of all creating the user, all I require is a username, password, and email for resetting their password if they forget it.

Creating a User with fields username, password, email.

Using Validate, I first validate the username, password, and emails (validation snippets down below). Validate is strange in that if everything is valid, it returns undefined, otherwise it returns the error message. So if both strings are undefined then I clean the username of any potential cross-site scripting attacks and store it in my new_user which is a MongoDB model.

I then check the password for XSS attacks and then generate a hash and store it in my new_user. Finally, the response I get back from the database after saving, I strip of all but the information the client needs (i.e. remove password information).

Generating the hash with bcrypt and mongoose
Remove any unnecessary information before sending it to the client

For token authorization, on the client side I am using the web API sessionStorage.

session storage on the client side

On the server side, jsonwebtoken is used to validate the token. The secret is stored in an environment variable and can be any random string.

Server side using jsonwebtoken to validate the token

And finally as promised, user input validation is performed with Validate.

User input validation

This website was very useful for integrating the token authorization into my React web application.

--

--