Files
llm-wiki/vault/20-evidence/official-docs/spring-security-authorize-http-requests.md
T

83 lines
9.8 KiB
Markdown

---
title: Spring Security — Authorize HttpServletRequests (AuthorizationFilter, request-level RBAC)
source_type: official-doc
url: https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html
archive_url:
related_branches: [feature-keycloak-spring-rs-role-mapping]
related_projects: [keycloak-patterns]
tags: [official-doc, keycloak-patterns, auth, spring-security]
created: 2026-07-18
last_reviewed: 2026-07-18
---
# Spring Security — Authorize HttpServletRequests (AuthorizationFilter, request-level RBAC)
> Layer: `raw/official-docs/` — Spring Security Reference `Authorize HttpServletRequests` 페이지의 verbatim 발췌.
> `feature-keycloak-spring-rs-role-mapping` 의 RBAC enforcement location Alternative A (`SecurityFilterChain.authorizeHttpRequests(...)` + `requestMatchers(...).hasRole(...)`) 결정의 1차 근거.
## Parent / 활용 branch (필수)
| Branch | 이 자료가 정당화하는 결정 |
|---|---|
| [[raw/branch-notes/feature-keycloak-spring-rs-role-mapping]] | RBAC enforcement location Alternative A — HTTP-request-level authorization via `SecurityFilterChain.authorizeHttpRequests(...)` + `requestMatchers("/api/admin/**").hasRole("admin-role")`. 정책을 하나의 config class 에 집중시키고, `AuthorizationFilter``DispatcherServlet` 이 컨트롤러로 dispatch 하기 *전에* 필터 체인에서 실행된다는 근거 |
## 출처 / Source
- 원본 URL: https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html
- 아카이브 URL: (미수집)
- 저자 / 조직: Spring Security (Broadcom / Spring team)
- 발행일: rolling docs (docs.spring.io 최신 stable 레퍼런스 — 특정 버전 고정 아님)
- 마지막 확인일: 2026-07-18
## 왜 저장했는지 / Why archived
`feature-keycloak-spring-rs-role-mapping``/api/admin``@PreAuthorize` 대신 `SecurityFilterChain` matcher 로 보호하기로 한 결정(D5)의 공식 근거를 확보하기 위해. 이 문서가 (a) request-level 권한 모델링 예시가 정확히 "/admin 아래 페이지는 authority 필요, 나머지는 인증만 필요" 패턴임을 확인시켜주고, (b) `AuthorizationFilter` 가 필터 체인에서 `DispatcherServlet` (즉 컨트롤러 실행) *이전에* 위치한다는 timing 근거를 제공하며, (c) `requestMatchers` 가 path 만 매칭하고 query parameter 는 매칭하지 않는다는 한계를 명시한다.
## 핵심 인용 / Key quotes (verbatim, 5문장)
> [§Authorize HttpServletRequests — intro] "For example, with Spring Security you can say that all pages under /admin require one authority while all other pages simply require authentication."
> [§AuthorizationFilter Is Last By Default] "The AuthorizationFilter is last in the Spring Security filter chain by default."
> [§AuthorizationFilter Is Last By Default] "Because they are executed by the DispatcherServlet and this comes after the AuthorizationFilter, your endpoints need to be included in authorizeHttpRequests to be permitted."
> [§Matching Using Ant] "Spring Security only matches paths."
> [§Matching Using Ant] "If you want to match query parameters, you will need a custom request matcher."
## Claims Extracted / 추출된 주장
| Claim ID | Claim (이 자료가 직접 말하는 것) | Evidence quote | Strength | Applies to | Does not prove |
|---|---|---|---|---|---|
| SS-AUTHZ-HTTP-C1 | Spring Security는 request-level 권한 모델링을 공식 지원하며, 그 대표 예시가 "특정 경로 하위는 authority 요구, 그 외는 인증만 요구" 패턴임 | "For example, with Spring Security you can say that all pages under /admin require one authority while all other pages simply require authentication." | `official-vendor-doc` | `SecurityFilterChain.authorizeHttpRequests(...)``/api/admin/**` 같은 sub-path 전용 authority 규칙을 선언하는 일반 패턴 | `admin-role` 이라는 구체적 role 이름이나 `/api/admin/**` glob 이 Spring 의 공식 권고라는 뜻은 아님 — 예시의 경로/이름은 illustrative |
| SS-AUTHZ-HTTP-C2 | `AuthorizationFilter` 는 **기본적으로 Spring Security 필터 체인의 마지막**에 위치함 | "The AuthorizationFilter is last in the Spring Security filter chain by default." | `official-vendor-doc` | 기본(customization 없는) `SecurityFilterChain` 구성의 필터 순서 이해 | 프로젝트가 커스텀 필터를 `AuthorizationFilter` 앞/뒤에 추가한 경우의 실제 순서까지 보장하지는 않음 — "기본값"이라는 전제 하의 진술 |
| SS-AUTHZ-HTTP-C3 | Spring MVC 엔드포인트는 `DispatcherServlet` 이 실행하며, 이는 `AuthorizationFilter` **이후**에 오므로, 그 엔드포인트가 보호받으려면 `authorizeHttpRequests` 규칙에 포함되어야 함 | "Because they are executed by the DispatcherServlet and this comes after the AuthorizationFilter, your endpoints need to be included in authorizeHttpRequests to be permitted." | `official-vendor-doc` | `SecurityFilterChain.authorizeHttpRequests(...)` 가 컨트롤러 코드 실행 전에 요청을 차단/허용하는 지점이라는 timing 근거 | `@PreAuthorize` 같은 method-level annotation 이 불필요하다거나 중복이라는 뜻은 아님 — 이 인용은 순서(ordering) 사실만 진술 |
| SS-AUTHZ-HTTP-C4 | `requestMatchers(...)` 등 Spring Security 의 기본 request matcher 는 **경로(path)만** 매칭함 | "Spring Security only matches paths." | `official-vendor-doc` | `requestMatchers("/api/admin/**")` 같은 path-glob 기반 matcher 설계의 한계 확인 | HTTP method 기반 matcher(`requestMatchers(HttpMethod.GET)`) 등 path 이외 매칭 수단이 전혀 없다는 뜻은 아님 — 이 인용은 query parameter 매칭 불가만 특정 |
| SS-AUTHZ-HTTP-C5 | Query parameter 를 인가 조건으로 매칭하려면 **custom request matcher** 를 직접 구현해야 함 (내장 API 없음) | "If you want to match query parameters, you will need a custom request matcher." | `official-vendor-doc` | RBAC 정책이 query parameter 에 의존하는 경우(예: `?print=true`) 설계 시 제약 인지 | `feature-keycloak-spring-rs-role-mapping``/api/admin/**` 규칙 자체는 path-only 이므로 이 한계에 직접 걸리지 않음 — 향후 query-param 기반 규칙 추가 시에만 관련 |
## Usage Boundaries / 적용 경계
- 이 자료가 직접 증명하는 것:
- `SS-AUTHZ-HTTP-C1`: request-level authorization 모델링(경로 기반 authority 규칙)이 Spring Security 의 공식 지원 패턴
- `SS-AUTHZ-HTTP-C2` + `SS-AUTHZ-HTTP-C3`: 기본 구성에서 `AuthorizationFilter``DispatcherServlet`(=컨트롤러 실행) **이전에** 실행되므로, `authorizeHttpRequests` 규칙이 컨트롤러 도달 전 1차 게이트임
- `SS-AUTHZ-HTTP-C4` + `SS-AUTHZ-HTTP-C5`: 기본 matcher 는 path-only 이며 query parameter 매칭은 custom `RequestMatcher` 가 필요
- 이 자료가 증명하지 않는 것:
- `SecurityFilterChain` matcher 방식이 `@PreAuthorize` 방식보다 "더 낫다"는 비교 우위 — 이 페이지는 request-level 메커니즘만 설명하며, method-level 과의 trade-off 비교는 [[raw/official-docs/spring-security-authorization-architecture]] 의 `SS-AUTHZ-ARCH-C4` (coarse-grained vs fine-grained 표)가 별도로 다룸
- "정책을 한 config class 에 집중시키는 것"이 공식 best practice 라는 진술 — 이는 branch 의 architectural 선호(D5)이며 본 자료가 직접 권고하지 않음
- `admin-role` 이라는 구체적 role 이름, `hasRole()``ROLE_` prefix 를 자동으로 붙인다는 세부 동작 — 이 페이지의 발췌 범위 밖 (별도 `hasRole`/`GrantedAuthority` 관련 페이지 확인 필요)
- 내 프로젝트에 적용하려면 추가 확인이 필요한 것:
- `feature-keycloak-spring-rs-role-mapping``SecurityFilterChain` 이 커스텀 필터를 추가하지 않는 기본 구성인지 (C2 의 "기본값" 전제가 실제로 성립하는지) 로컬 검증 필요
- `/api/admin` 엔드포인트가 `FORWARD`/`ERROR` dispatch 를 사용하는 뷰 렌더링·예외 처리 경로를 갖는다면, 본 문서의 "All Dispatches Are Authorized" 섹션(본 자료에서 인용하지 않은 별도 caveat — 메모 참고)에 따라 재검토 필요
## 메모 / Notes
- 본 페이지에는 "AuthorizationFilter runs not just on every request, but on every dispatch" (`§All Dispatches Are Authorized`) 라는 별도 섹션이 있음 — `REQUEST` 뿐 아니라 `FORWARD`/`ERROR`/`INCLUDE` 디스패치에도 인가가 재실행된다는 내용. 이번 5개 핵심 인용에는 포함하지 않았으나(범위 밖), `/api/admin` 이 뷰 forward 나 에러 핸들러를 거치는 구현이라면 이 부분을 별도로 self-grep 재확인 후 인용 추가 권장.
- `hasRole("admin-role")` 표기의 `ROLE_` prefix 자동 부여 여부는 이 페이지가 아니라 sibling 자료 [[raw/official-docs/spring-security-authorization-architecture]] 의 `SS-AUTHZ-ARCH-C5` 가 다룸 ("By default, role-based authorization rules include ROLE_ as a prefix.") — 중복 인용 대신 링크로 참조.
- 페이지 코드 예시(`.requestMatchers("/api/admin/**").hasRole("ADMIN")`)는 branch 의 `/api/admin/**` + `hasRole("admin-role")` 형태와 구조적으로 동일 — 다만 role 이름 대문자 컨벤션(`ADMIN` vs `admin-role`)은 이 문서가 강제하지 않음 (INFERENCE 아님, 단순 미언급).
## Related / 관련
- [[raw/official-docs/spring-security-authorization-architecture]] — `AuthorizationManager` 아키텍처 + coarse-grained(request-level) vs fine-grained(method-level) trade-off 표, `ROLE_` prefix 기본값
- [[raw/official-docs/spring-security-resource-server-jwt]] — JWT `aud`/`iss` 검증 + `realm_access.roles` → Spring authority 매핑 (본 branch 의 audience-validator sibling 근거)
- [[raw/branch-notes/feature-keycloak-spring-rs-role-mapping]]