К основному содержанию
скилл CX Codex официальный · GitHub

spring-security — скилл для GitHub Copilot: настройка и установка

Скилл для GitHub Copilot помогает настраивать, тестировать и проверять Spring Security. Подключается при добавлении или аудите аутентификации и авторизации в приложении Spring Boot.

MIT ★ 41 430 обновлён 2026-10-23

Установить в GitHub Copilot · GitHub CLI Все способы и платформы ↓
gh skill install github/awesome-copilot skills/spring-security
Открыть на GitHub

Что делает spring-security

Скилл помогает настроить SecurityFilterChain, защиту методов, JWT и вход через OIDC, а также проверить CSRF, CORS, пароли и доступ к actuator. Для тестов он описывает сценарии с MockMvc и проверки ответов 401, 403 и 200.

Сначала нужно определить версии Spring Boot и Spring Security и тип приложения: servlet MVC или WebFlux, браузерное сессиями или API без состояния. Для Boot 3.x используется Spring Security 6.x, для Boot 4.x — 7.x; инструкции для этих версий различаются. В Boot 4.x старые имена OAuth2-стартеров доступны как устаревшие псевдонимы.

Какие задачи решает

  • настроить правила доступа через SecurityFilterChain
  • добавить авторизацию на уровне методов
  • выбрать схему защиты для API или браузерного приложения
  • проверить ответы 401, 403 и 200 в тестах
  • найти открытые endpoints и ошибки в настройках безопасности

Примеры запросов агенту

  • Настрой SecurityFilterChain для моего API с JWT и ролями.
  • Проверь настройки Spring Security в приложении Spring Boot 4 и найди открытые endpoints.
  • Добавь тесты безопасности с MockMvc для ответов 401, 403 и 200.

Как установить spring-security

1GitHub CLI

gh skill install github/awesome-copilot skills/spring-security

2Вручную: положить файлы

.github/skills/spring-security/SKILL.md

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о spring-security

Как установить spring-security в GitHub Copilot?

Выполни gh skill install github/awesome-copilot skills/spring-security. Файл скилла появится по пути .github/skills/spring-security/SKILL.md.

Что делает spring-security?

Скилл помогает настраивать и проверять аутентификацию и авторизацию в приложениях Spring Boot: от правил SecurityFilterChain до тестов безопасности.

Какую версию Spring Security использует spring-security?

Он охватывает Spring Security 6.x для Spring Boot 3.x и Spring Security 7.x для Spring Boot 4.x. Рекомендации зависят от версии: например, в 7.x удалены некоторые API, устаревшие в 6.x.

Исходный текст

SKILL.md · MIT
---
name: spring-security
description: 'Configure, test and review Spring Security 6/7 in Spring Boot 3/4 apps: SecurityFilterChain lambda DSL, method security, OAuth2 resource server with JWT, OIDC login, CSRF/CORS, password encoding, headers, actuator protection, and MockMvc security tests. Use when adding or auditing authentication and authorization.'
---

# Spring Security

Practical guidance for Spring Security 6.x (Spring Boot 3.x) and 7.x (Spring Boot 4.x). Details per topic are in `references/`.

## Safety rules

- Never read, print, or commit secrets: `.env`, `application-*.properties` with credentials, client secrets, private keys, JWT signing keys. Reference them via environment variables or a secret manager.
- Never disable security (`permitAll()` on everything, `csrf.disable()` for browser apps) just to make a test or demo pass.

## First: detect the version

1. Find the Boot version (`pom.xml` parent/BOM, `build.gradle(.kts)`, `libs.versions.toml`) and run `./mvnw dependency:tree -Dincludes=org.springframework.security` or `./gradlew dependencies --configuration runtimeClasspath` to see the Spring Security version.
2. Boot 3.x -> Security 6.x; Boot 4.x -> Security 7.x. Do not mix guidance: in 7.x, APIs deprecated in 6.x are removed (for example `and()` chaining, `authorizeRequests`, `AntPathRequestMatcher`/`MvcRequestMatcher` style matchers; use the lambda DSL and `requestMatchers(...)`). Check the "What's New" and migration pages on docs.spring.io/spring-security when upgrading.
3. Identify the app type: servlet MVC (`SecurityFilterChain`) or WebFlux (`SecurityWebFilterChain`, `@EnableWebFluxSecurity`); browser app with sessions, or stateless API.

## Core configuration

Declare a `SecurityFilterChain` bean. `WebSecurityConfigurerAdapter` no longer exists.

```java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**", "/public/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable()); // only for stateless token APIs without cookies
        return http.build();
    }
}
```

Rules of thumb:

- Rules are evaluated in order; put specific matchers first and end with `anyRequest().authenticated()` (deny by default).
- Use multiple `SecurityFilterChain` beans with `securityMatcher(...)` and `@Order` when the app mixes an API and a browser UI.
- Add `@EnableMethodSecurity` and use `@PreAuthorize`/`@PostAuthorize` on services for fine-grained rules; see [method security](references/method-security.md).
- Authentication choices: [OAuth2 resource server and JWT](references/oauth2-resource-server-jwt.md), [OIDC login and OAuth2 client](references/oidc-login-oauth2-client.md).
- Session vs stateless, CSRF, CORS, headers: [web protections](references/csrf-cors-sessions-headers.md).
- Passwords and users: [password encoding](references/password-encoding.md).
- Actuator endpoints: [actuator protection](references/actuator-protection.md) (see also the `spring-observability` skill if installed).
- Tests: [testing security](references/testing-security.md).
- Review: [common mistakes checklist](references/review-checklist.md).

## Decision guide

| Situation | Approach |
|---|---|
| REST API called by SPA/mobile/services with bearer tokens | Resource server + JWT, stateless, CSRF off (no cookie auth) |
| Server-rendered app or SPA with same-site cookie session | Form login or OIDC login, sessions, CSRF on |
| SPA using BFF pattern | OIDC login in the backend, session cookie to browser, CSRF token via cookie repository |
| Internal service-to-service | Client credentials grant, resource server on the receiving side |

## Dependencies (pin through the Boot BOM, no explicit versions)

- `spring-boot-starter-security`, plus `spring-boot-starter-oauth2-resource-server` or `spring-boot-starter-oauth2-client` on Boot 3.x. Boot 4.x names: `spring-boot-starter-security-oauth2-resource-server` / `spring-boot-starter-security-oauth2-client` (the old names remain as deprecated aliases).
- Tests: add `spring-security-test` (test scope) on Boot 3.x; on Boot 4.x use `spring-boot-starter-security-test` (plus `spring-boot-starter-security-oauth2-resource-server-test` / `-client-test` when those starters are used) together with modular test starters such as `spring-boot-starter-webmvc-test`.

## Verify

Run the app's tests plus security-specific tests (401 without credentials, 403 with insufficient role, 200 with the right one, CSRF rejection on state-changing browser requests). Confirm no endpoint was accidentally left open by listing the mappings and checking each against the filter chain.

See also (prefer over this skill for the version in use): Spring Security reference <https://docs.spring.io/spring-security/reference/index.html> and migration chapter <https://docs.spring.io/spring-security/reference/migration/index.html>.

© github · MIT · github/awesome-copilot

Похожие скиллы

Все скиллы по теме «Безопасность» →
spring-boot-security-jwt giuseppe-trisciuoglio Скилл spring-boot-security-jwt с готовыми шаблонами JWT-аутентификации для Spring Boot 3.5.x: генерация токенов через JJWT, фильтры, RBAC и OAuth2. CX Codex +1 4 400установок 304-frameworks-spring-boot-security Juan Antonio Breña Moral Скилл 304-frameworks-spring-boot-security настраивает защиту приложений на Spring Boot, отладку SecurityFilterChain и авторизацию API. Помогает внедрить JWT, проверку ролей и заголовки безопасности. CX Codex +1 328установок java-spring-boot pluginagentmarketplace Скилл java-spring-boot помогает создавать бэкенд на Spring Boot 3: настраивать REST API, аутентификацию через Spring Security, доступ к базам через Spring Data и мониторинг Actuator. CX Codex +1 11 800установок spring-boot-engineer https://github.com/Jeffallan Скилл spring-boot-engineer разворачивает архитектуру Spring Boot 3.x, контроллеры, репозитории Spring Data JPA и правила Spring Security 6. Пригодится при сборке REST API, реактивных сервисов и микросервисов на Java. CX Codex +1 8 900установок spring-boot-actuator giuseppe-trisciuoglio Скилл помогает настроить Spring Boot Actuator: добавить пробы жизнеспособности для оркестраторов, защитить служебные эндпоинты и экспортировать метрики Micrometer в Prometheus. CX Codex +1 4 000установок java-spring-development Mindrally Скилл java-spring-development для Claude Code помогает писать приложения на Spring Boot по рекомендациям для структуры проекта, API, безопасности и тестирования. Активируется при задачах по разработке на Java и Spring. CX Codex +1 978установок

Из того же набора993

Весь набор →
pr-address-feedback Скилл pr-address-feedback пошагово разбирает замечания ревью в пулл-реквесте, группирует похожие комментарии и готовит план правок до изменения файлов. Пригодится при разборе ревью в ветке. CX Codex +1 2установок java-testcontainers Скилл java-testcontainers помогает писать интеграционные тесты на Java с Testcontainers 2.x и JUnit Jupiter, поднимая базы данных и очереди в Docker. Пригодится при настройке тестов или миграции с ветки 1.x. CX Codex +1 1установок java-debugging Скилл java-debugging для GitHub Copilot ведёт агента по методике поиска причины бага в Java: воспроизвести, сузить, проверить гипотезу, подключить отладчик. Использует логи и логпоинты вместо брейкпоинтов. CX Codex +1 1установок supabase-rls-policies Скилл supabase-rls-policies для GitHub Copilot помогает писать, проверять и тестировать политики Row Level Security в Supabase. Запускается при создании таблиц, правке миграций и настройке изоляции пользователей. CX Codex +1 ★ 41 430звёзд репо spring-observability Скилл spring-observability для GitHub Copilot настраивает наблюдаемость в сервисах на Spring Boot 3 и 4. Включается при добавлении метрик Micrometer, трассировки OpenTelemetry и структурированных логов с Actuator. CX Codex +1 ★ 41 430звёзд репо spring-boot-4-migration Скилл spring-boot-4-migration для GitHub Copilot переносит приложение со Spring Boot 3.x на 4.0. Запускается для миграции, разбора вызванных ею ошибок сборки и тестов или проверки уже выполненного перехода. CX Codex +1 ★ 41 430звёзд репо skill-distribution-audit Скилл skill-distribution-audit для GitHub Copilot проверяет репозитории со скиллами перед релизом. Сверяет исходные файлы с манифестом дистрибуции и реальной поисковой выдачей клиента. CX Codex +1 ★ 41 430звёзд репо scout-issue Скилл scout-issue для GitHub Copilot подбирает GitHub issues для вклада в открытые проекты. Он спрашивает об опыте, навыках, времени и типе вклада, затем ранжирует подходящие задачи. CX Codex +1 ★ 41 430звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой