0Pricing
Spring Security 6 & JWT Authentication · Урок

Распространённые уязвимости безопасности и способы их устранения

Научитесь выявлять и устранять распространённые уязвимости веб-приложений, такие как XSS, CSRF и внедрение SQL, в контексте Spring Security.

«Распространённые уязвимости безопасности и способы их устранения» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Web Vulnerabilities Overview

Welcome! In this lesson, we'll dive into common web application security vulnerabilities. Understanding these threats is crucial for building robust and secure applications.

Even with frameworks like Spring Security, knowing how common attacks work helps you write safer code and configure your app effectively.

What is Cross-Site Scripting?

Cross-Site Scripting (XSS) occurs when attackers inject malicious scripts (usually JavaScript) into web pages viewed by other users.

These scripts can steal session cookies, deface websites, or redirect users to phishing sites. It tricks the user's browser into executing untrusted code.

Reflected, Stored, and DOM XSS

XSS comes in a few flavors:

  • Reflected XSS: Malicious script is part of the request (e.g., URL parameter) and immediately 'reflected' back in the response.
  • Stored XSS: Malicious script is permanently stored on the target server (e.g., in a database via a comment field) and served to all visitors.
  • DOM-based XSS: The vulnerability lies in client-side code modifying the Document Object Model (DOM) based on user input, rather than server-side generation.

XSS Prevention: Input & Output

The best defenses against XSS are:

  • Input Validation: On the server, strictly validate and sanitize all user input. Don't trust anything coming from the client.
  • Output Encoding: Before displaying user-supplied data in HTML, always 'escape' it. This turns malicious code into harmless text, preventing the browser from executing it.

Spring frameworks often provide utilities for output encoding.

Encoding User Input

Here's a simple Java example demonstrating output encoding. Notice how special HTML characters like < and > are converted to their entity equivalents (&lt;, &gt;).

This makes the script harmless when rendered in a browser.

import org.springframework.web.util.HtmlUtils;

public class XssPrevention {
  public static void main(String[] args) {
    String userInput = "<script>alert('You are hacked!');</script>";
    String safeOutput = HtmlUtils.htmlEscape(userInput);

    System.out.println("Original: " + userInput);
    System.out.println("Encoded: " + safeOutput);
  }
}

What is Cross-Site Request Forgery?

Cross-Site Request Forgery (CSRF) is an attack that tricks a logged-in user into submitting a request they did not intend. For example, changing their password or making a purchase.

The attacker crafts a malicious web page that sends a request to your application, and if the user is logged in, their browser automatically includes authentication credentials (like cookies).

Spring Security's CSRF Defense

Spring Security provides robust, built-in CSRF protection. By default, it generates a unique, synchronized token (a CSRF token) for each session.

This token must be included in non-GET requests (like POST, PUT, DELETE). If the token is missing or invalid, Spring Security rejects the request, preventing CSRF attacks.

What is SQL Injection?

SQL Injection (SQLi) is a common attack where malicious SQL code is inserted into input fields to manipulate backend database queries.

Attackers can use SQLi to bypass authentication, retrieve sensitive data, modify data, or even take control of the database server. It's often exploited when an application constructs SQL queries using concatenated strings.

SQLi Prevention: Parameterized Queries

The primary defense against SQL Injection is using parameterized queries (also known as prepared statements).

Instead of concatenating user input directly into the SQL string, placeholders are used. The database then treats user input as data, not as executable SQL code, neutralizing the attack.

import java.sql.*;

public class SqlInjectionPrevention {
  public static void main(String[] args) {
    String username = "admin' OR '1'='1"; // Malicious input

    // GOOD: Parameterized Query (Safe concept)
    String goodSql = "SELECT * FROM users WHERE username = ?";
    System.out.println("Safe SQL (PreparedStatement concept): " + goodSql);
    System.out.println("Parameter used: " + username);
    // In a real app, 'username' would be set as a parameter
    // on a PreparedStatement object.
  }
}

Vulnerability Check

Which of the following is the most effective way to prevent SQL Injection attacks?

Lesson Summary

Great job! You've explored three critical web vulnerabilities and their fixes:

  • XSS: Prevent with input validation and output encoding.
  • CSRF: Spring Security handles this by default with CSRF tokens.
  • SQL Injection: Prevent with parameterized queries (prepared statements).

Always remember to validate all input, encode all output, and leverage your framework's built-in security features!

Часто задаваемые вопросы

Урок «Распространённые уязвимости безопасности и способы их устранения» бесплатный?

Да — полный текст урока «Распространённые уязвимости безопасности и способы их устранения» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Чему я научусь в уроке «Распространённые уязвимости безопасности и способы их устранения»?

Научитесь выявлять и устранять распространённые уязвимости веб-приложений, такие как XSS, CSRF и внедрение SQL, в контексте Spring Security. Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?

Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Распространённые уязвимости безопасности и способы их устранения»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?

Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Усиление защиты в рабочей среде
  2. Ведение журналов и мониторинг событий безопасности
  3. Распространённые уязвимости безопасности и способы их устранения
  4. Настройка заголовков безопасности и HTTPS
← Назад к Spring Security 6 & JWT Authentication