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

Защита конечных точек с помощью настраиваемых правил доступа

Выйдите за рамки простых проверок ролей: напишите собственную логику авторизации в Spring Security 6 с использованием AuthorizationManager, выражений SpEL и сопоставителей запросов

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

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

Why Custom Access Rules?

Roles and methods cover most cases, but real apps need finer control: only the owner of a resource may edit it, or access depends on the time of day or a feature flag.

Spring Security 6 lets you express these rules declaratively or programmatically.

The authorizeHttpRequests DSL

In Spring Security 6 the modern way to secure URLs is authorizeHttpRequests. Each matcher maps a request pattern to an access rule.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/public/**').permitAll()
    .requestMatchers('/admin/**').hasRole('ADMIN')
    .anyRequest().authenticated());

Matching by HTTP Method

You can scope rules to a specific HTTP method, so reads and writes have different requirements.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers(HttpMethod.GET, '/api/orders/**').authenticated()
    .requestMatchers(HttpMethod.POST, '/api/orders/**').hasRole('MANAGER'));

SpEL with access()

The access() rule takes a Spring Expression Language (SpEL) condition for dynamic logic that plain matchers cannot express.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/reports/**')
    .access(new WebExpressionAuthorizationManager(
        "hasRole('ANALYST') and request.getHeader('X-Region') == 'EU'")));

The AuthorizationManager Interface

For full control, implement AuthorizationManager. It returns an AuthorizationDecision that grants or denies access based on the authentication and the request.

public interface AuthorizationManager<T> {
    AuthorizationDecision check(Supplier<Authentication> auth, T object);
}

Writing a Custom AuthorizationManager

Here is a manager that only allows access during business hours. The supplier gives the current user; the object holds request context.

AuthorizationManager<RequestAuthorizationContext> businessHours =
    (auth, ctx) -> {
        int hour = LocalTime.now().getHour();
        boolean ok = hour >= 9 && hour < 18;
        return new AuthorizationDecision(ok);
    };

Plugging It In

Attach your custom manager to a matcher with access(). Any request to the path is now evaluated by your logic.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/maintenance/**').access(businessHours)
    .anyRequest().authenticated());

Owner-Based Access

A common rule: only the resource owner can modify it. You can read a path variable from the request context to compare against the logged-in user.

AuthorizationManager<RequestAuthorizationContext> ownerOnly =
    (auth, ctx) -> {
        String pathUser = ctx.getVariables().get('userId');
        boolean same = auth.get().getName().equals(pathUser);
        return new AuthorizationDecision(same);
    };

Combining Rules

Spring evaluates matchers top to bottom and stops at the first match. Order matters: put specific rules before broad ones, and always end with a catch-all like anyRequest().

Denying by Default

A secure baseline denies everything not explicitly allowed. Use denyAll() as the final rule when you want a strict allow-list.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers('/health').permitAll()
    .anyRequest().denyAll());

Testing Access Rules

Verify your rules with @WithMockUser and MockMvc. Assert that authorized users get 200 and unauthorized users get 403.

mockMvc.perform(get('/admin/dashboard'))
    .andExpect(status().isForbidden());

Quick Check

Test your understanding of custom access rules.

Recap

You learned to write custom authorization in Spring Security 6:

  • Use the authorizeHttpRequests DSL with path and method matchers
  • Apply SpEL conditions via access()
  • Implement AuthorizationManager for dynamic, owner-based, or time-based rules
  • Order matters; end with a catch-all and prefer deny-by-default

These tools let you enforce business-specific security policies precisely.

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

Урок «Защита конечных точек с помощью настраиваемых правил доступа» бесплатный?

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

Чему я научусь в уроке «Защита конечных точек с помощью настраиваемых правил доступа»?

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

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

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

Сколько времени занимает урок «Защита конечных точек с помощью настраиваемых правил доступа»?

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

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

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

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

  1. Управление доступом на основе ролей (RBAC)
  2. Безопасность на уровне методов с аннотациями
  3. Подробная настройка HttpSecurity
  4. Защита конечных точек с помощью настраиваемых правил доступа
← Назад к Spring Security 6 & JWT Authentication