avatarCaleb

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3975

Abstract

span>(<span class="hljs-string">"Connected!"</span>);

<span class="hljs-comment">// create a parameterized query</span> <span class="hljs-keyword">var</span> sql = <span class="hljs-string">"SELECT * FROM customers WHERE address = ?"</span>; <span class="hljs-keyword">var</span> inserts = [<span class="hljs-string">'Mountain 21'</span>]; sql = mysql.<span class="hljs-title function_">format</span>(sql, inserts);

con.<span class="hljs-title function_">query</span>(sql, <span class="hljs-keyword">function</span> (<span class="hljs-params">err, result</span>) { <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err; <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); }); });</pre></div><h1 id="502c">Cross Site Scripting (XSS)</h1><p id="8fcc">Cross Site Scripting attacks occur when an attacker is able to inject a malicious script into your web page, which can then run in other users’ browsers.</p><p id="559f">To prevent XSS attacks, always validate and sanitize inputs. Do not include HTML tags in user inputs. For example, you can sanitize HTML input in Express.js using the “express-validator” middleware:</p><div id="0de8"><pre><span class="hljs-keyword">var</span> express = <span class="hljs-keyword">require</span>(<span class="hljs-string">'express'</span>); <span class="hljs-keyword">var</span> { check, validationResult } = <span class="hljs-keyword">require</span>(<span class="hljs-string">'express-validator'</span>);

<span class="hljs-keyword">var</span> app = <span class="hljs-title function_ invoke__">express</span>();

app.<span class="hljs-keyword">use</span>(express.<span class="hljs-title function_ invoke__">json</span>());

app.<span class="hljs-title function_ invoke__">post</span>(<span class="hljs-string">'/user'</span>, [ <span class="hljs-title function_ invoke__">check</span>(<span class="hljs-string">'username'</span>).<span class="hljs-title function_ invoke__">trim</span>().<span class="hljs-title function_ invoke__">escape</span>() ], function(req, res) { <span class="hljs-comment">// Check for validation errors</span> <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">errors</span> = <span class="hljs-title function_ invoke__">validationResult</span>(req);

<span class="hljs-comment">// If there are errors, return them in the response</span> <span class="hljs-keyword">if</span> (!errors.<span class="hljs-title function_ invoke__">isEmpty</span>()) { <span class="hljs-keyword">return</span> res.<span class="hljs-title function_ invoke__">status</span>(<span class="hljs-number">400</span>).<span class="hljs-title function_ invoke__">json</span>({ <span class="hljs-attr">errors</span>: errors.<span class="hljs-keyword">array</span>() }); }

<span class="hljs-comment">// No errors, continue with processing</span> <span class="hljs-comment">// Example: just send a success message</span> res.<span class="hljs-title function_ invoke__">json</span>({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Data processed successfully"</span> }); });</pre></div><h1 id="4ec9">Conclusion</h1><p id="fef0">Web security is a vast and ever-changing field, with new threats and solutions appearing all the time. But with some solid fundamentals in place, we can build and protect our websites against common attacks.</p><p id="2f0c">As developers, we bear the responsibility of not just building functional and aesthetically pleasing websites, but also securing the data and privacy of our users. I hope this article has been helpful in understanding and implementing some of these basic security measures.</p><p id="fc6b">Let’s keep learning, keep questioning, and keep our web spaces safe.</p><p id="b6a3"><i>Thank you for reading until the end. Please consider following the writer and this publication. Visit <a href="https://stackademic.c

Options

om/">Stackademic</a> to find out more about how we are democratizing free programming education around the world.</i></p><p id="a412"><i>Web Security Basics</i></p><ul><li><a href="https://owasp.org/www-project-top-ten/"><i>OWASP Top 10</i></a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Security"><i>Mozilla Developer Network Web Security Guide</i></a></li></ul><p id="1497"><i>HTTPS and Secure Communications</i></p><ul><li><a href="https://letsencrypt.org/getting-started/"><i>Let’s Encrypt</i></a></li><li><a href="https://nodejs.org/api/https.html"><i>Node.js HTTPS documentation</i></a></li></ul><p id="7f12"><i>SQL Injection</i></p><ul><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"><i>OWASP SQL Injection Prevention Cheat Sheet</i></a></li><li><a href="https://github.com/mysqljs/mysql#escaping-query-values"><i>MySQL Node.js driver’s escaping query values</i></a></li></ul><p id="8745"><i>Cross Site Scripting (XSS)</i></p><ul><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"><i>OWASP XSS Prevention Cheat Sheet</i></a></li></ul><p id="eb3a"><i>Node.js with Express</i></p><ul><li><a href="https://expressjs.com/"><i>Express.js official website</i></a></li><li><a href="https://express-validator.github.io/docs/"><i>Express Validator Middleware</i></a></li></ul><div id="98fd" class="link-block"> <a href="https://medium.com/@calebpr/subscribe"> <div> <div> <h2>Get an email whenever Caleb publishes.</h2> <div><h3>Get an email whenever Caleb publishes. By signing up, you will create a Medium account if you don’t already have one…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*pPSGj3ORvqLvuBYg)"></div> </div> </div> </a> </div><p id="91bd"><i>Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:</i></p><div id="7e3a" class="link-block"> <a href="https://readmedium.com/a-roadmap-to-my-medium-writings-fd04e14cffd7"> <div> <div> <h2>A Roadmap to My Medium Writings</h2> <div><h3>undefined</h3></div> <div><p>undefined</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*FO4S90VIpPA05s9cP-gFPQ.png)"></div> </div> </div> </a> </div><p id="8496"><i>If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.</i></p><p id="c73a"><i>[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. <a href="https://readmedium.com/how-does-ai-help-me-write-my-articles-5df265d16527">To know more about my creative process, read this article.</a>]</i></p><div id="a005" class="link-block"> <a href="https://readmedium.com/how-does-ai-help-me-write-my-articles-5df265d16527"> <div> <div> <h2>How Does AI Help Me Write My Articles?</h2> <div><h3>The Medium landscape has seen a transformation, with an increasing number of articles appearing to have the distinct…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*sURudlO3SS5ntthELFumcg.jpeg)"></div> </div> </div> </a> </div></article></body>

Why Cyber Criminals Wish You Won’t Read This: Protecting Your Website from Cyber Threats

Hi there! I’ve been working as a JavaScript developer for years now, and I’ve spent quite a bit of that time getting to grips with web security. I’m not going to sugarcoat it, it can be tough, but it’s also an essential part of what we do.

I’m sharing this guide with you based on my own experiences. I’ve made mistakes and learned lessons, and now I hope those lessons can help you. Security might seem daunting at first, but don’t hesitate to ask questions or seek help. No one gets it perfect from the start. Let’s get into it.

HTTPS and Secure Communications

The first step towards securing your website is making sure that your users’ data is transmitted securely. HTTPS, which stands for HyperText Transfer Protocol Secure, encrypts data sent between your users and your website.

If you’re using JavaScript for server-side scripting with Node.js, implementing HTTPS is relatively straightforward:

var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("Welcome to the secure side of the web!");
}).listen(8000);

Remember to replace ‘test/fixtures/keys/agent2-key.pem’ and ‘test/fixtures/keys/agent2-cert.pem’ with the file paths of your SSL certificate and private key, respectively. Now, your Node.js app will be able to handle HTTPS requests.

SQL Injection

SQL Injection is a type of security threat where an attacker could inject malicious SQL code using the input fields on your website. This could potentially allow them to manipulate your database.

Using Parameterized queries or prepared statements helps mitigate this risk. Here’s an example using Node.js and MySQL:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

  // create a parameterized query
  var sql = "SELECT * FROM customers WHERE address = ?";
  var inserts = ['Mountain 21'];
  sql = mysql.format(sql, inserts);

  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});

Cross Site Scripting (XSS)

Cross Site Scripting attacks occur when an attacker is able to inject a malicious script into your web page, which can then run in other users’ browsers.

To prevent XSS attacks, always validate and sanitize inputs. Do not include HTML tags in user inputs. For example, you can sanitize HTML input in Express.js using the “express-validator” middleware:

var express = require('express');
var { check, validationResult } = require('express-validator');

var app = express();

app.use(express.json());

app.post('/user', [
  check('username').trim().escape()
], function(req, res) {
  // Check for validation errors
  const errors = validationResult(req);
  
  // If there are errors, return them in the response
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  
  // No errors, continue with processing
  // Example: just send a success message
  res.json({ message: "Data processed successfully" });
});

Conclusion

Web security is a vast and ever-changing field, with new threats and solutions appearing all the time. But with some solid fundamentals in place, we can build and protect our websites against common attacks.

As developers, we bear the responsibility of not just building functional and aesthetically pleasing websites, but also securing the data and privacy of our users. I hope this article has been helpful in understanding and implementing some of these basic security measures.

Let’s keep learning, keep questioning, and keep our web spaces safe.

Thank you for reading until the end. Please consider following the writer and this publication. Visit Stackademic to find out more about how we are democratizing free programming education around the world.

Web Security Basics

HTTPS and Secure Communications

SQL Injection

Cross Site Scripting (XSS)

Node.js with Express

Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:

If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.

[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. To know more about my creative process, read this article.]

Cybersecurity
Programming
JavaScript
Technology
Learning To Code
Recommended from ReadMedium