Spring Security 6 & JWT Authentication · Урок

Понимание цепочки фильтров Spring Security

Загляните внутрь Spring Security 6, чтобы понять, как цепочка фильтров сервлетов обрабатывает каждый запрос и какое место в ней занимает аутентификация

Урок 4 из 413 шагов

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

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

How Requests Get Secured

So how does every request actually get checked? The security filter chain — a series of servlet filters Spring slots in before your controllers.

What Is a Servlet Filter?

A servlet Filter intercepts HTTP requests and responses before they reach your code. Spring Security is built almost entirely from these filters.

The DelegatingFilterProxy

The real servlet filter, DelegatingFilterProxy, hands each request to a Spring-managed bean — bridging the servlet world and the Spring context.

The FilterChainProxy

Behind that proxy sits FilterChainProxy, which holds one or more SecurityFilterChain instances and routes each request to the one that matches.

Key Filters in Order

Filters run in a fixed order: SecurityContextHolderFilter loads context, the auth filter handles login, and AuthorizationFilter enforces access rules.

Defining a SecurityFilterChain Bean

In Spring Security 6 you configure everything by declaring a SecurityFilterChain bean — the modern replacement for WebSecurityConfigurerAdapter. See below.

@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .formLogin(Customizer.withDefaults());
    return http.build();
}

Where the SecurityContext Lives

After login, the Authentication is stored in the SecurityContext and stays reachable via SecurityContextHolder for the rest of the request.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

Permitting Some Paths

Let public paths through while securing the rest — all on the same chain. The code uses permitAll() for /public and authenticated() for everything else.

http.authorizeHttpRequests(a -> a
    .requestMatchers('/public/**').permitAll()
    .anyRequest().authenticated());

Multiple Filter Chains

Register several SecurityFilterChain beans with securityMatcher so API and web paths get different rules. The first matching chain wins.

http.securityMatcher('/api/**');

Adding a Custom Filter

Slot your own filter at a precise position with addFilterBefore — the foundation for the JWT processing you'll build later in this course.

http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class);

Why This Matters

Knowing the chain explains why ordering matters, where auth versus authz happens, and exactly where a custom JWT filter has to plug in.

Quick Check

In Spring Security 6, how do you define your security configuration?

Recap

Recap: requests flow DelegatingFilterProxy to FilterChainProxy to SecurityFilterChain; filters run in order, auth then authz, and addFilterBefore inserts custom ones.

Можно начать бесплатно

Изучай Java с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

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

Урок «Понимание цепочки фильтров Spring Security» бесплатный?

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

Чему я научусь в уроке «Понимание цепочки фильтров Spring Security»?

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

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

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

Сколько времени занимает урок «Понимание цепочки фильтров Spring Security»?

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

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

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

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

  1. Введение в Spring Security 6
  2. Настройка проекта и зависимости
  3. Аутентификация пользователей в памяти
  4. Понимание цепочки фильтров Spring Security
← Назад к Spring Security 6 & JWT Authentication