Web application security: 10 best practices for 2024

Web application security: 10 best practices for 2024

Web application security has become a major concern for any business with an online presence. Cyberattacks are getting both more frequent and more sophisticated, putting sensitive data and company reputations at risk. This article goes through the best practices for protecting your web applications against current and future threats.

Understanding the main threats

The most common attacks

Before getting to the solutions, you need to understand the main types of attack that threaten web applications:

  1. SQL injection: this technique consists of slipping malicious code into SQL queries to manipulate the database.
  2. Cross-Site Scripting (XSS): attackers inject malicious scripts into web pages viewed by other users.
  3. Brute force attacks: attackers try to guess credentials by working through a large number of combinations.

How threats evolved in 2024

Cybercriminals adapt their techniques constantly. In 2024 we are seeing a resurgence of targeted attacks and growing use of artificial intelligence to automate and refine intrusion attempts.

The fundamentals of securing a web application

Implementing robust authentication

Solid authentication is the first line of defence against unauthorised access.

  • Secure password hashing: use modern hashing algorithms such as bcrypt or Argon2 to store passwords.

Here is a PHP example using password_hash() and password_verify():

php
// Hash the password at sign-up
$password = $_POST['password'];
$hashedPassword = password_hash($password, PASSWORD_ARGON2ID);

// Store $hashedPassword in the database

// Check the password at login
$storedHash = // Fetch the stored hash from the database
if (password_verify($_POST['password'], $storedHash)) {
    // Password correct
} else {
    // Password incorrect
}
  • Multi-factor authentication (2FA/MFA): add an extra layer of security by requiring more than one form of identification.

Secure session management

Put mechanisms in place to protect user sessions:

  • Generate random, complex session identifiers.
  • Expire sessions after a period of inactivity.
  • Use secure cookies with the HttpOnly and Secure attributes
php
// Configure secure session options
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 1);

// Generate a new session ID on every login
session_regenerate_id(true);

// Set a session lifetime
ini_set('session.gc_maxlifetime', 3600); // 1 hour
  • Multi-factor authentication (2FA/MFA): add an extra layer of security by requiring more than one form of identification.

Validating and sanitising user input

Every piece of user input has to be treated as potentially dangerous:

  • Validate all input strictly, on the server side.
  • Use allow lists to filter the characters you accept.
  • Escape data properly before putting it into an SQL query or into HTML.
php
// Example of validating and sanitising an email address
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // The email address is not valid
}

// Example of protection against SQL injection using prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
$user = $stmt->fetch();

Protecting sensitive data

Encrypting data in transit and at rest

Encryption is essential for protecting sensitive information:

  • Use TLS 1.3 to secure communication between the client and the server.
  • Encrypt sensitive data stored in the database.
php
// Encryption
$plaintext = "Données sensibles à chiffrer";
$cipher = "aes-256-cbc";
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$encrypted = openssl_encrypt($plaintext, $cipher, $key, 0, $iv);

// Decryption
$decrypted = openssl_decrypt($encrypted, $cipher, $key, 0, $iv);

Setting up HTTPS/SSL

HTTPS is no longer optional, it is a requirement:

  • Get a valid SSL/TLS certificate from a recognised certificate authority.
  • Configure your server to redirect all HTTP traffic to HTTPS automatically.
.htaccess
php
# Rediriger HTTP vers HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Securing your APIs

APIs are often critical entry points:

  • Require strong authentication for API access.
  • Rate-limit requests to prevent abuse.
  • Use JWT (JSON Web Tokens) to manage API sessions securely.
    • Set up a systematic process for applying security patches.
    • Subscribe to the security bulletins published by your software vendors.

Security training and awareness

      • Run regular training sessions on the latest security techniques.
      • Teach your users good security habits (strong passwords, spotting phishing, and so on).

    Compliance and security standards

        • Make sure your web application meets the regulations that apply to it (GDPR, PCI DSS, and so on).
        • Use the OWASP Top 10 as your reference for finding and fixing the most critical vulnerabilities.

      Conclusion

      Securing a web application is a continuous process that demands constant attention. Adopt these best practices and you will considerably strengthen your applications against current and future cyberthreats.

        • Run penetration tests at least once a year, and after every major change.
        • Put a web application firewall (WAF) in front of the application to block many common attacks.
        • Set up alerts for suspicious activity.
        • Keep logs long enough to be useful for forensic analysis.

      Vulnerability management and updates

          • Set up a systematic process for applying security patches.
          • Subscribe to the security bulletins published by your software vendors.

        Security training and awareness

            • Run regular training sessions on the latest security techniques.
            • Teach your users good security habits (strong passwords, spotting phishing, and so on).

          Compliance and security standards

              • Make sure your web application meets the regulations that apply to it (GDPR, PCI DSS, and so on).
              • Use the OWASP Top 10 as your reference for finding and fixing the most critical vulnerabilities.

            Conclusion

            Securing a web application is a continuous process that demands constant attention. Adopt these best practices and you will considerably strengthen your applications against current and future cyberthreats.

              • Train your developers in secure coding techniques.
              • Use frameworks and libraries with a good security record.
              • Run regular code reviews focused on security.
              • Keep an up-to-date inventory of every dependency.
              • Use automated tooling to find vulnerabilities in third-party libraries.
              • Apply defence in depth by securing every layer of the infrastructure.

            Testing and continuous monitoring

                • Run penetration tests at least once a year, and after every major change.
                • Put a web application firewall (WAF) in front of the application to block many common attacks.
                • Set up alerts for suspicious activity.
                • Keep logs long enough to be useful for forensic analysis.

              Vulnerability management and updates

                  • Set up a systematic process for applying security patches.
                  • Subscribe to the security bulletins published by your software vendors.

                Security training and awareness

                    • Run regular training sessions on the latest security techniques.
                    • Teach your users good security habits (strong passwords, spotting phishing, and so on).

                  Compliance and security standards

                      • Make sure your web application meets the regulations that apply to it (GDPR, PCI DSS, and so on).
                      • Use the OWASP Top 10 as your reference for finding and fixing the most critical vulnerabilities.

                    Conclusion

                    Securing a web application is a continuous process that demands constant attention. Adopt these best practices and you will considerably strengthen your applications against current and future cyberthreats.

                    php
                    function hasPermission($userId, $action) {
                        $userRole = getUserRole($userId); // Function to get the user role
                        $permissions = [
                            'admin' => ['read', 'write', 'delete'],
                            'editor' => ['read', 'write'],
                            'viewer' => ['read']
                        ];
                    
                    return in_array($action, $permissions[$userRole] ?? []);
                    }
                    
                    // Usage
                    if (hasPermission($userId, 'write')) {
                        // Allow the write action
                    } else {
                        // Deny access
                    }

                    Code and infrastructure security

                        • Train your developers in secure coding techniques.
                        • Use frameworks and libraries with a good security record.
                        • Run regular code reviews focused on security.
                        • Keep an up-to-date inventory of every dependency.
                        • Use automated tooling to find vulnerabilities in third-party libraries.
                        • Apply defence in depth by securing every layer of the infrastructure.

                      Testing and continuous monitoring

                          • Run penetration tests at least once a year, and after every major change.
                          • Put a web application firewall (WAF) in front of the application to block many common attacks.
                          • Set up alerts for suspicious activity.
                          • Keep logs long enough to be useful for forensic analysis.

                        Vulnerability management and updates

                            • Set up a systematic process for applying security patches.
                            • Subscribe to the security bulletins published by your software vendors.

                          Security training and awareness

                              • Run regular training sessions on the latest security techniques.
                              • Teach your users good security habits (strong passwords, spotting phishing, and so on).

                            Compliance and security standards

                                • Make sure your web application meets the regulations that apply to it (GDPR, PCI DSS, and so on).
                                • Use the OWASP Top 10 as your reference for finding and fixing the most critical vulnerabilities.

                              Conclusion

                              Securing a web application is a continuous process that demands constant attention. Adopt these best practices and you will considerably strengthen your applications against current and future cyberthreats.

                                Access control and permissions

                                The principle of least privilege

                                Give every user and every process only the rights they need to carry out their specific tasks.

                                Putting an effective access control policy in place

                                A simple example of role-based access control:

                                php
                                function hasPermission($userId, $action) {
                                    $userRole = getUserRole($userId); // Function to get the user role
                                    $permissions = [
                                        'admin' => ['read', 'write', 'delete'],
                                        'editor' => ['read', 'write'],
                                        'viewer' => ['read']
                                    ];
                                
                                return in_array($action, $permissions[$userRole] ?? []);
                                }
                                
                                // Usage
                                if (hasPermission($userId, 'write')) {
                                    // Allow the write action
                                } else {
                                    // Deny access
                                }

                                Code and infrastructure security

                                    • Train your developers in secure coding techniques.
                                    • Use frameworks and libraries with a good security record.
                                    • Run regular code reviews focused on security.
                                    • Keep an up-to-date inventory of every dependency.
                                    • Use automated tooling to find vulnerabilities in third-party libraries.
                                    • Apply defence in depth by securing every layer of the infrastructure.

                                  Testing and continuous monitoring

                                      • Run penetration tests at least once a year, and after every major change.
                                      • Put a web application firewall (WAF) in front of the application to block many common attacks.
                                      • Set up alerts for suspicious activity.
                                      • Keep logs long enough to be useful for forensic analysis.

                                    Vulnerability management and updates

                                        • Set up a systematic process for applying security patches.
                                        • Subscribe to the security bulletins published by your software vendors.

                                      Security training and awareness

                                          • Run regular training sessions on the latest security techniques.
                                          • Teach your users good security habits (strong passwords, spotting phishing, and so on).

                                        Compliance and security standards

                                            • Make sure your web application meets the regulations that apply to it (GDPR, PCI DSS, and so on).
                                            • Use the OWASP Top 10 as your reference for finding and fixing the most critical vulnerabilities.

                                          Conclusion

                                          Securing a web application is a continuous process that demands constant attention. Adopt these best practices and you will considerably strengthen your applications against current and future cyberthreats.

                                          php
                                          function generateToken($userId) {
                                              $payload = [
                                                  'user_id' => $userId,
                                                  'exp' => time() + 3600 // Expires in 1 hour
                                              ];
                                              return jwt_encode($payload, 'votre_clé_secrète');
                                          }
                                          
                                          function verifyToken($token) {
                                              try {
                                                  $payload = jwt_decode($token, 'votre_clé_secrète');
                                                  if ($payload->exp < time()) {
                                                      return false; // Token expired
                                                  }
                                                  return $payload->user_id;
                                              } catch (Exception $e) {
                                                  return false; // Invalid token
                                              }
                                          }
                                          
                                          // Use in an API route
                                          $token = getBearerToken(); // Function to extract the token from the header
                                          $userId = verifyToken($token);
                                          if ($userId === false) {
                                              http_response_code(401);
                                              echo json_encode(['error' => 'Unauthorized']);
                                              exit;
                                          }
                                          // Carry on processing the API request

                                            Access control and permissions

                                            The principle of least privilege

                                            Give every user and every process only the rights they need to carry out their specific tasks.

                                            Putting an effective access control policy in place

                                            A simple example of role-based access control:

                                            php
                                            function hasPermission($userId, $action) {
                                                $userRole = getUserRole($userId); // Function to get the user role
                                                $permissions = [
                                                    'admin' => ['read', 'write', 'delete'],
                                                    'editor' => ['read', 'write'],
                                                    'viewer' => ['read']
                                                ];
                                            
                                            return in_array($action, $permissions[$userRole] ?? []);
                                            }
                                            
                                            // Usage
                                            if (hasPermission($userId, 'write')) {
                                                // Allow the write action
                                            } else {
                                                // Deny access
                                            }

                                            Code and infrastructure security

                                                • Train your developers in secure coding techniques.
                                                • Use frameworks and libraries with a good security record.
                                                • Run regular code reviews focused on security.
                                                • Keep an up-to-date inventory of every dependency.
                                                • Use automated tooling to find vulnerabilities in third-party libraries.
                                                • Apply defence in depth by securing every layer of the infrastructure.

                                              Testing and continuous monitoring

                                                  • Run penetration tests at least once a year, and after every major change.
                                                  • Put a web application firewall (WAF) in front of the application to block many common attacks.
                                                  • Set up alerts for suspicious activity.
                                                  • Keep logs long enough to be useful for forensic analysis.

                                                Vulnerability management and updates

                                                    • Set up a systematic process for applying security patches.
                                                    • Subscribe to the security bulletins published by your software vendors.

                                                  Security training and awareness

                                                      • Run regular training sessions on the latest security techniques.
                                                      • Teach your users good security habits (strong passwords, spotting phishing, and so on).

                                                    Compliance and security standards

                                                        • Make sure your web application meets the regulations that apply to it (GDPR, PCI DSS, and so on).
                                                        • Use the OWASP Top 10 as your reference for finding and fixing the most critical vulnerabilities.

                                                      Conclusion

                                                      Securing a web application is a continuous process that demands constant attention. Adopt these best practices and you will considerably strengthen your applications against current and future cyberthreats.

                                                      Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
                                                      Newsletter

                                                      New tests, tutorials and projects, by e-mail.

                                                      Reproducible tests, versioned code, dated results. Never any spam.