Cybersecurity
A05 Security Misconfiguration
CORS

A05:2021 - Security Misconfiguration

ℹ️

For the information about Security Misconfiguration, visit page (opens in a new tab)

CORS

πŸ”

CWE-942: Overly Permissive Cross-domain Whitelist

About

CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. To put it in simple words, when a web browser tries to access resources on a different domain, it sends an HTTP request to the server hosting the resource. If the server does not allow requests from that domain, the browser will block the response and the web application will not be able to access the resource.

Demo

  1. In the jwtAuth.ts file, comment out the line app.use(cors()); in server.ts file and try to log in to the HackHealth account.
  2. As you can see, the login is not successful, and if we open in browser the Developer Tools (Ctrl + Shift + I) -> Console, we get the message like this:
️🚫

Access to fetch at 'http://localhost:5000/auth/verify (opens in a new tab)' from origin 'http://localhost:3001 (opens in a new tab)' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource...

When setting up the web server, we included the cors library and added the following line of code: app.use(cors()); This action was deliberately left uncommented in the tutorial because it is meant to show one important thing. Even experienced software engineers sometimes just copy some parts of code and are generally not fully aware of the consequences it can have on the application and its security.

πŸ’‘

Now, uncomment the line app.use(cors()); and try to log in to the HackHealth account again.

Your login should be successful.

Prevention

We are developing everything locally, so we do not have to be aware of the risks of CORS attacks. However, when we deploy our application to the production environment, we should be aware of the security risks and take appropriate measurements. You should always define the origins of the requests that are allowed to access your API.

  1. Add the following variable to the file jwtAuth.ts.
jwtAuth.ts
const options = {
   origin: 'http://localhost:3001'}
  1. Pass the options object to the cors function. app.use(cors(options));

By doing so, we are allowing only requests from the origin http://localhost:3001 to access our API. All other requests will be blocked by the CORS policy.

Sources