Files
technical-visualization-haness/.work/keycloak-four-patterns/final/document.md
T
2026-07-29 18:03:21 +09:00

107 KiB
Raw Blame History

브라우저 토큰에서 엣지 세션까지: Keycloak 인증 패턴 네 가지의 경계 설계

코드보다 먼저 드러난 문제

사용자가 로그인한 뒤 자신의 정보를 조회하는 장면을 하나 고정해 보자. 브라우저가 보호된 화면에 들어가고, Keycloak 로그인 화면에서 regular-user로 인증한 다음, 애플리케이션은 결국 다음과 비슷한 JSON을 화면에 보여 준다.

{
  "subject": "<keycloak-user-id>",
  "username": "regular-user"
}

화면과 최종 값만 보면 네 구현은 같은 일을 하는 것처럼 보인다. 그러나 최초 입력에서 최종 출력까지 코드를 따라가면 네 시스템은 서로 다른 credential과 서로 다른 호출 주체를 사용한다.

  • AP1에서는 브라우저가 authorization code를 token으로 바꾸고 Authorization: Bearer ...를 직접 만든다.
  • AP2에서는 Spring mediator가 code를 token으로 바꾸고 refresh token을 보관하지만, access token은 JSON으로 브라우저에 넘긴다. 브라우저가 그 값을 다시 Bearer header로 바꿔 API를 호출한다.
  • AP3에서는 BFF가 code 교환과 token 보관뿐 아니라 API 호출까지 맡는다. 브라우저가 보내는 입력은 OAuth token이 아니라 session cookie이고, BFF가 그 입력을 downstream Bearer 요청으로 변환한다.
  • AP4에서는 oauth2-proxy가 OIDC client가 되고, Nginx가 session 유효성을 내부 서브리퀘스트로 묻는다. 성공 결과는 token이 아니라 사용자·이메일 header로 바뀌며, Spring upstream은 그 header와 내부 인증값을 입력으로 받는다.

이 차이를 “Keycloak을 붙이는 네 가지 방법”이라고만 설명하면 중요한 설계 비용이 보이지 않는다. 브라우저 token을 없애려고 BFF를 선택했는데 session store와 CSRF 방어를 준비하지 않을 수 있다. 기존 애플리케이션을 거의 고치지 않으려고 forward-auth를 선택했는데 외부에서 위조 가능한 identity header를 그대로 믿을 수도 있다. 반대로 요청별 JWT 검증과 browser-to-API 직접 호출이 중요한데 token을 숨긴다는 이유만으로 BFF를 추가하면 원래 없던 state와 장애 지점이 생긴다.

그래서 이 글은 네 패턴을 다음 질문으로 읽는다.

최초 HTTP 입력은 무엇인가? 그 입력을 어느 코드가 받는가? code·token·cookie·header는 어느 지점에서 다른 데이터로 변환되는가? 다음 홉은 무엇을 입력으로 받고, 최종 HTTP 출력은 누가 만드는가?

이 질문을 로그인 단계와 로그인 후 API 단계에 각각 적용한다. “누가 OAuth client인가”만 확인하지 않고, 실제 endpoint, 클래스와 메서드, 중간 데이터, 성공 응답, 실패 응답까지 한 요청을 끝까지 추적한다. 그렇게 해야 AP1부터 AP4까지가 보안 등급표가 아니라 OAuth 책임과 신뢰 경계를 서로 다른 위치에 배치한 네 가지 설계라는 사실이 드러난다.

문제를 어렵게 만든 제약

로그인 흐름과 API 흐름은 같은 선이 아니다

Authorization Code 흐름에는 최소 두 개의 왕복이 있다. 먼저 authorization request가 Keycloak로 가고, 사용자 인증 뒤 authorization code가 redirect URI로 돌아온다. 그다음 OAuth client가 token endpoint에 code를 제출한다. PKCE를 쓰는 client는 첫 요청에 code_challenge를, token request에 code_verifier를 제출하고, confidential client는 client 인증도 수행한다.

로그인이 끝난 다음 API 요청은 별개의 흐름이다. Access token을 발급받은 주체와 API를 실제 호출하는 주체가 같을 수도 있고 다를 수도 있다. AP2에서는 mediator가 token을 발급받지만 브라우저가 API를 호출한다. AP3에서는 BFF가 발급받고 BFF가 호출한다. AP4에서는 oauth2-proxy가 OIDC code 교환과 AP4_SESSION 검증을 맡지만 upstream 요청을 연결하고 identity header를 조립하는 주체는 Nginx다.

따라서 Browser → Keycloak → API처럼 한 줄로 그리면 code의 이동, token의 이동, API credential의 이동이 섞인다. 이 글에서는 각 패턴을 다음 두 구간으로 분리한다.

  1. 로그인 구간: authorization request, callback, code 교환, 로그인 상태 생성
  2. 애플리케이션 요청 구간: 브라우저 입력, 중간 계층의 credential 변환, 보호 자원의 검증, 최종 응답

로그인 구간과 애플리케이션 요청 구간을 나누어 AP2 mediator·브라우저, AP3 BFF, AP4 oauth2-proxy·Nginx의 책임 배치를 비교한 다이어그램.

Diagram description

왼쪽 로그인 구간에는 Keycloak과 AP2 mediator, AP3 BFF, AP4 oauth2-proxy가 있다. Keycloak의 authorization code는 각 OAuth client 쪽으로 이동한다. 오른쪽 애플리케이션 요청 구간에는 AP2 브라우저, AP3 BFF, AP4 Nginx와 보호 자원이 있다. AP2는 token을 받는 mediator와 API를 호출하는 브라우저가 갈리고, AP3는 같은 BFF가 token 발급과 API 호출을 소유한다. AP4는 oauth2-proxy가 code 교환과 session 검증을 맡고 Nginx가 upstream 요청 연결과 identity header 조립을 맡는다.

Editable source · Grounded VizSpec

같은 사용자를 나타내도 데이터의 의미는 다르다

네 패턴에서 regular-user라는 값은 여러 형태로 나타난다. 이 값들을 모두 “인증 정보”라고 부르면 어느 계층이 무엇을 검증했는지 사라진다.

데이터 만든 주체 주된 소비자 의미
authorization code Keycloak OAuth client 짧게 사용되는 code 교환 입력
PKCE verifier AP1 SPA, AP3 BFF, AP4 oauth2-proxy Keycloak token endpoint authorization request를 시작한 client와 code 교환 주체를 연결
access token Keycloak Resource Server API 요청을 인증·인가하는 Bearer credential
refresh token Keycloak AP1 SPA, AP2 mediator, AP3 BFF 등 해당 소유자 새 access token을 얻는 장기 credential
server session 식별 cookie mediator 또는 BFF 같은 server-side login state의 소유자 브라우저 요청을 HttpSession 인증 상태에 연결
proxy session cookie oauth2-proxy oauth2-proxy의 auth endpoint AP4의 minimal client-side session 상태를 다음 auth subrequest에 제시
CSRF token AP3 BFF AP3 BFF cookie가 자동 첨부되는 상태 변경 요청의 의도 확인
identity header oauth2-proxy 결과를 받은 Nginx AP4 upstream edge가 확인한 사용자 identity의 투영
internal auth token AP4 배포 설정 AP4 upstream 허용된 edge를 거쳤다는 추가 신뢰 신호

Access token의 preferred_username claim과 AP4의 X-Auth-Request-User가 같은 문자열을 담을 수는 있다. 하지만 첫 번째는 Resource Server가 서명·issuer·audience를 검증해야 하는 JWT 안의 claim이고, 두 번째는 upstream이 신뢰 가능한 edge 경로와 내부 인증값을 확인한 뒤에만 받아들여야 하는 header다. 값이 같다고 신뢰 근거까지 같아지는 것은 아니다.

“브라우저에 없다”도 무엇이 없는지 구분해야 한다

AP3와 AP4에서 JavaScript가 OAuth token을 받지 않는다는 설명은 맞지만, 브라우저에 인증 상태가 전혀 없다는 뜻은 아니다. 브라우저는 HttpOnly session cookie를 보유하고 요청 때 자동으로 보낸다. AP3에서는 상태 변경 요청을 위해 JavaScript가 읽을 수 있는 별도의 XSRF-TOKEN도 사용한다. 또한 네 패턴 모두 Keycloak 도메인의 SSO cookie가 존재할 수 있다. 이 글의 저장 위치 비교는 애플리케이션이 사용하는 credential에 한정하며, IdP 자체의 SSO 상태를 “없음”으로 계산하지 않는다.

반대로 AP1에서 Web Storage에 token을 쓰지 않는다는 말도 JavaScript가 token을 볼 수 없다는 뜻은 아니다. Access·refresh·ID token은 실행 중 memory에 있고, 악성 script가 같은 실행 문맥에서 fetch를 가로채거나 API를 대신 호출할 수 있다. Memory-only 선택이 줄이는 것은 reload 뒤 남는 persistent script-readable 복사본이지, 실행 중 XSS의 권한이 아니다.

AP1부터 AP4까지 OAuth credential 소유자, 브라우저 credential, 보관 모델과 현재 입증된 운영 범위를 같은 네 축으로 정렬한 비교 다이어그램.

Diagram description

왼쪽부터 AP1, AP2, AP3, AP4를 읽는다. 각 항목은 OAuth credential 소유자, 브라우저에 남는 애플리케이션 credential, 보관 모델, shared durability나 replica 운영에 관한 현재 근거를 같은 순서로 제시한다. AP1의 access·refresh·ID token은 실행 중 JavaScript memory에 있고 persistent Web Storage 복사본만 줄인다. AP2는 refresh token을 mediator가 소유하고 server session 식별 cookie를 사용하지만 shared durable store는 입증되지 않았다. AP3는 refresh token을 BFF가 소유하며 브라우저에는 HttpOnly session과 readable XSRF token이 남는다. AP4는 minimal client-side proxy session을 사용하고 replica cookie secret 공유와 rotation은 검증되지 않았다.

Editable source · Grounded VizSpec

현재 구현은 운영 참조 아키텍처가 아니라 관찰 가능한 학습 환경이다

현재 구성은 Keycloak 26.7.0과 oauth2-proxy 7.15.2를 사용한 로컬 단일 인스턴스 환경이다. HTTP에서 cookie 속성과 redirect를 관찰하기 위해 일부 운영 기본값과 다른 설정을 쓴다. AP2와 AP3의 session·authorized-client 저장은 shared durable store로 입증되지 않았다. AP4는 별도 server-side session store 대신 minimal client-side cookie를 쓰며, replica 사이의 cookie secret 공유·rotation과 재인증 lifecycle은 검증되지 않았다.

그러므로 이 문서가 코드에서 확인할 수 있는 것은 다음 범위다.

  • 어느 endpoint와 handler가 요청을 받는가
  • 어느 계층이 code를 교환하고 access·refresh token을 보유하는가
  • 브라우저에 어떤 cookie 또는 token 응답이 도달하는가
  • API로 전달되는 header와 최종 JSON 모양은 무엇인가
  • 커밋된 자동 테스트가 어떤 acceptance contract를 선언하는가

반면 처리량, 장애 복구 시간, session failover, secret rotation 절차, 실제 Google 계정과 public HTTPS redirect의 성공 여부는 여기서 증명하지 않는다. 구현되지 않은 운영 속성을 패턴 이름에서 추론해 채워 넣지 않는 것이 네 패턴을 공정하게 비교하기 위한 첫 번째 제약이다.

검토한 선택지와 막힌 지점

책임과 데이터를 같은 표에 놓기

먼저 로그인과 API 요청의 주체를 같은 축으로 비교한다.

비교 축 AP1 · SPA direct AP2 · token mediator AP3 · BFF AP4 · edge forward-auth
OAuth client 브라우저의 public SPA Spring mediator Spring BFF oauth2-proxy
client 종류 public confidential confidential confidential
code 교환 주체 브라우저 mediator BFF oauth2-proxy
PKCE S256 현재 client 등록·흐름에서 명시적 AP1/AP3/AP4 가드레일과 동일하게 주장하지 않음 S256 S256
refresh token 소유자 브라우저 JavaScript memory mediator의 authorized client BFF의 authorized client 지속 보관 근거 없음: oauth2-proxy가 code/token 교환은 하지만 minimal cookie에는 access·refresh·ID token을 저장하지 않고 refresh lifecycle도 검증되지 않음
access token이 JavaScript 응답에 포함되는가 포함 포함 미포함 미포함
API를 호출하는 주체 브라우저 브라우저 BFF Nginx가 upstream 요청을 연결
보호 자원이 받는 credential Bearer JWT Bearer JWT BFF가 붙인 Bearer JWT user·email header + internal token
애플리케이션 측 로그인 상태 server session 없음 AP2_SESSION + authorized client AP3_SESSION + authorized client minimal client-side AP4_SESSION을 사용하는 proxy 경계
새로 필요한 핵심 방어 browser token 수명주기·XSS 피해 축소 access 응답 제한·CORS·server state 운영 CSRF·session scale-out·token-at-rest network isolation·header overwrite·service identity

AP2의 PKCE 칸을 일부러 다른 패턴과 동일하게 채우지 않았다. “Authorization Code를 쓴다”와 “현재 구현이 PKCE S256까지 같은 방식으로 고정했다”는 서로 다른 주장이다. 코드와 설정에서 확인한 범위보다 넓혀 네 패턴을 억지로 대칭적으로 만들지 않는다.

다음 표는 로그인 뒤 한 번의 애플리케이션 요청에서 실제로 이동하는 데이터를 보여 준다.

패턴 브라우저가 보내는 입력 중간 계층이 조회·생성하는 데이터 보호 자원의 실제 입력 브라우저가 받는 출력
AP1 Authorization: Bearer <access_token> 없음 동일 Bearer JWT /api/me JSON
AP2 먼저 AP2_SESSION, 다음에 Bearer access token mediator가 authorized client에서 access token을 읽어 JSON으로 반환 브라우저가 다시 만든 Bearer JWT token JSON, 이어서 /api/me JSON
AP3 AP3_SESSION; POST에는 X-XSRF-TOKEN 추가 BFF가 authorized client에서 access token을 읽고 downstream Bearer header 생성 BFF가 보낸 Bearer JWT BFF가 중계한 JSON
AP4 AP4_SESSION Nginx auth subrequest, oauth2-proxy의 user·email 결과, 배포 secret 정제된 identity header + internal token /edge/me가 만든 identity JSON

AP1, AP2, AP3, AP4의 브라우저 입력, 중간 변환, 보호 자원 credential과 브라우저 출력을 같은 네 축으로 비교한 다이어그램.

Diagram description

왼쪽부터 AP1 SPA direct, AP2 token mediator, AP3 BFF, AP4 edge forward-auth를 읽는다. 각 항목은 브라우저가 보내는 입력, 중간 계층의 변환, 보호 자원이 실제로 받는 credential, 브라우저가 받는 출력을 같은 순서로 보여 준다. AP1과 AP2는 브라우저가 Bearer JWT로 API를 직접 호출하고, AP3는 BFF가 Bearer JWT를 조립하며, AP4는 Nginx가 인증 결과를 identity header와 internal token으로 바꾼다.

Editable source · Grounded VizSpec

AP1에서 막히는 지점: protocol 투명성과 browser credential

AP1은 가장 적은 중간 계층으로 OAuth와 Resource Server 계약을 보여 준다. 그만큼 authorization code, verifier, access token, refresh token과 logout 요청이 JavaScript 실행 경계에 들어온다. InMemoryWebStorage를 선택하면 reload 뒤 token 상태 유지를 포기하는 대신 persistent Web Storage 복사본을 줄일 수 있다. 그러나 실행 중 XSS가 현재 Bearer token을 관찰하거나 사용자의 권한으로 API를 호출하는 문제는 남는다. PKCE는 탈취한 authorization code의 교환을 어렵게 하는 장치이지, 발급이 끝난 access token을 XSS로부터 감추는 저장소가 아니다.

Local Storage나 Session Storage에 token을 저장하면 reload 편의를 얻지만 노출 수명도 길어진다. HttpOnly cookie로 바꾸면 단순한 저장 방식 변경이 아니라 server가 session 또는 token 중계를 소유하는 AP3 계열 경계로 이동한다. 이 구현은 교육 목적의 protocol 가시성을 위해 AP1을 유지하고, 짧은 access token 수명, refresh rotation, issuer·audience 검증을 함께 둔다.

AP2에서 막히는 지점: access-only이지만 tokenless는 아니다

AP2는 client secret과 refresh token을 browser 밖으로 옮기면서도 browser-to-API Bearer 계약을 유지하려는 절충이다. 이 구조에는 두 종류의 상태가 동시에 존재한다. 브라우저는 mediator login을 위한 AP2_SESSION을 보내고, mediator가 반환한 access token도 memory에서 사용한다. Server state 운영비와 browser access-token 노출이 모두 남는 이유다.

현재 access endpoint는 access token 원문, token type, 만료 시각을 반복해서 반환할 수 있다. Nonce를 발급하고 한 번 소비한 뒤 token을 삭제하는 로직은 없다. 따라서 이를 one-time handoff라고 부르면 구현보다 강한 replay 속성을 발명하게 된다. 정확한 이름은 access-only handoff다. Refresh token을 반환하지 않는다는 경계와 access token 전달이 한 번뿐이라는 경계는 별개다.

AP3에서 막히는 지점: tokenless browser가 만드는 stateful backend

AP3는 JavaScript 응답에서 OAuth token을 없앤다. 그 대신 모든 API 요청이 BFF를 지나고, BFF가 session으로 authorized client를 찾아 downstream 요청을 만든다. 브라우저는 bearer credential을 조립하지 않지만 cookie를 자동 첨부한다. 그래서 상태 변경 endpoint는 CSRF token을 별도 header로 확인해야 한다.

현재 학습 구현의 session과 authorized-client state는 단일 인스턴스 전제를 벗어난 durable shared store로 확인되지 않았다. 재시작 뒤 로그인 지속, 여러 replica 사이의 요청 이동, 저장 token 암호화, coordinated logout은 별도 설계 항목이다. BFF라는 이름 자체가 이 운영 문제를 해결해 주지는 않는다.

AP4에서 막히는 지점: token 대신 header를 믿는 조건

AP4는 OAuth/OIDC를 모르는 upstream 앞에서 공통 login gate를 만들 수 있다. 그러나 upstream이 받은 X-Auth-Request-User가 단순한 client 입력인지, edge가 인증 뒤 만든 값인지 구분할 수 있어야 한다. Backend port가 외부에 열려 있거나 Nginx가 client header를 그대로 통과시키면 공격자는 인증된 identity를 흉내 낼 수 있다.

현재 hardened 예시는 세 조건을 결합한다. Nginx만 host에 publish하고 app과 oauth2-proxy는 내부 network에 둔다. Nginx가 user·email·internal-token header를 항상 자기 값으로 덮어쓴다. 마지막으로 /edge/me controller가 user header와 internal token을 함께 확인한다. 이 마지막 검증은 현재 한 controller에만 구현되어 있다. /edge/** 전체를 Spring Security filter가 보호한다고 일반화하면 안 되며, endpoint가 늘어나면 공통 filter 또는 security chain으로 중앙화해야 한다.

선택의 이유와 지킨 경계

AP1: OAuth와 JWT 계약을 가장 가까이서 관찰한다

상황과 제약은 명확하다. Browser에서 Authorization Code + PKCE, token 응답, refresh rotation, logout과 Resource Server의 JWT 검증을 직접 학습해야 한다. 이 목적에서는 SPA가 public OAuth client가 되는 AP1이 network와 code의 인과관계를 가장 잘 드러낸다.

선택은 spa-public client와 Authorization Code + PKCE S256이다. Implicit flow와 direct access grant는 끄고, API는 Keycloak의 서명만 보는 것이 아니라 issuer, 시간 제약, keycloak-pattern-api audience를 함께 검증한다. Realm role은 Spring의 ROLE_ authority로 변환한다.

대안은 refresh custody만 mediator로 옮기는 AP2와 모든 token을 BFF로 옮기는 AP3다. 하지만 두 대안은 browser에서 code 교환과 token 수명주기를 직접 관찰하려는 학습 목적을 흐린다. AP1이 수용한 비용은 access·refresh·ID token이 JavaScript memory에 존재하고 reload 뒤 인증 상태를 복구하지 않는다는 점이다.

가드레일은 비용을 없애지는 않지만 범위를 줄인다. Token의 persistent Web Storage 복사본을 만들지 않고, access token 수명을 300초로 두며, refresh token rotation과 reuse 0을 사용한다. Resource Server는 잘못된 issuer나 audience를 401로 거부한다. 그래도 실행 중 XSS의 same-origin 권한과 이미 발급된 access JWT의 만료 전 유효성은 남는 위험이다.

SPA, Keycloak, 브라우저 JavaScript memory, Resource Server가 왼쪽에서 오른쪽으로 연결된 AP1 직접 인증 아키텍처.

Diagram description

왼쪽의 public SPA가 Keycloak과 Authorization Code 및 PKCE S256 계약을 수행한다. Keycloak token 응답의 access, refresh, ID token은 브라우저 JavaScript memory에 놓이며, 그중 access JWT가 오른쪽 Resource Server의 검증 입력이 된다. Resource Server는 issuer, 시간 제약과 keycloak-pattern-api audience를 검증한다.

Editable source · Grounded VizSpec

AP2: refresh credential은 서버에, 직접 API 호출은 브라우저에 둔다

상황은 browser가 Resource Server를 직접 호출하는 계약을 유지해야 하지만 client secret과 refresh token을 JavaScript에 맡기고 싶지 않은 경우다. 선택은 confidential mediator가 Spring oauth2Login으로 code를 교환하고 access·refresh token을 server-side authorized-client service에 저장하는 구조다.

브라우저에는 HttpOnly AP2_SESSION과 별도로 현재 access token만 전달한다. Access 응답 필드는 access_token, token_type, expires_at으로 제한하고 Cache-Control: no-storePragma: no-cache를 붙인다. 브라우저는 값을 memory에서 읽어 Resource Server용 Bearer header를 만든다.

Server state가 불가능하다면 AP1이 더 일관된 대안이다. Browser token을 허용할 수 없다면 AP3가 더 일관된다. AP2가 수용한 비용은 mediator session과 authorized-client 저장을 운영하면서도 access token의 JavaScript 노출은 남는다는 점이다. 좁은 CORS origin과 method, refresh token 비반환, session cookie의 HttpOnly·SameSite, downstream audience 검증이 보완 가드레일이다. 반복 access handoff 제한, durable store, logout과 만료 후 refresh 동작은 현재 입증된 가드레일에 포함되지 않는다.

브라우저가 Spring mediator에서 access token만 받아 Resource Server를 직접 호출하고 refresh token은 authorized-client store에 남기는 AP2 split-custody 아키텍처.

Diagram description

브라우저는 AP2_SESSION으로 confidential Spring mediator의 login state를 사용한다. Mediator는 code를 교환한 뒤 access와 refresh token을 server-side authorized-client service에 저장한다. 현재 access token의 값, type, expiry만 브라우저로 전달되고 refresh token은 server 경계에 남는다. 브라우저는 memory에 있는 access token으로 Resource Server용 Bearer header를 만든다.

Editable source · Grounded VizSpec

AP3: browser token 비노출과 application-owned session을 맞바꾼다

상황은 JavaScript가 OAuth token을 받아서는 안 되고, 사용자별 API 조합과 애플리케이션 인가를 backend 경계에 모으려는 경우다. 선택은 bff-confidential client, Spring oauth2Login, server-side authorized client, 그리고 BFF endpoint다.

BFF가 access·refresh token을 보관하며 브라우저에는 HttpOnly AP3_SESSION만 OAuth login credential로 남긴다. 브라우저의 /bff/api/me 요청을 받은 BFF가 현재 authorized client를 조회해 내부 Resource Server용 Bearer 요청으로 바꾼다. 상태 변경 요청에는 XSRF-TOKEN cookie의 값을 X-XSRF-TOKEN header로 되돌려 보내게 하고 server가 일치 여부를 확인한다.

AP1은 stateless Resource Server와 protocol 가시성을 얻는 대안이고, AP2는 direct browser-to-API 호출을 유지하는 대안이다. AP3가 수용한 비용은 session affinity 또는 shared store, 모든 API fan-out의 latency와 장애 지점, CSRF, logout 및 token-at-rest 보호다. 현재 구현은 이 비용을 단일 인스턴스 memory와 한 개의 예시 BFF 호출로 보여 줄 뿐, Redis나 암호화 저장소까지 완성하지 않는다.

Browser session zone과 server-side BFF zone 사이에서 AP3_SESSION이 downstream Bearer 요청으로 바뀌는 BFF 아키텍처.

Diagram description

왼쪽 browser session zone에는 OAuth token 없이 HttpOnly AP3_SESSION을 가진 브라우저가 있다. 오른쪽 server-side application zone에는 BFF, authorized-client store, 내부 Resource Server가 있다. 브라우저의 /bff/api/me 요청은 BFF에서 종료되고, BFF는 current authorized client를 조회해 server-held access token으로 Resource Server용 Bearer 요청을 조립한다.

Editable source · Grounded VizSpec

AP4: OAuth를 모르는 upstream 앞에서 신뢰 경로를 만든다

상황은 기존 upstream을 OAuth client나 JWT Resource Server로 크게 바꾸기 어렵고 여러 경로에 공통 login gate를 적용하려는 경우다. 선택은 confidential edge-proxy client, oauth2-proxy의 minimal cookie session, Nginx auth_request 조합이다. OIDC code 교환과 provider token 검증은 oauth2-proxy가 맡고, Nginx는 매 요청의 session 유효성을 확인한 뒤 allowlist된 identity 정보만 upstream으로 보낸다.

애플리케이션이 사용자별 API orchestration과 세밀한 인가를 적극적으로 소유해야 한다면 AP3가 더 자연스러운 대안이다. Traefik ForwardAuth도 policy point 대안이지만 OIDC client와 session manager 자체는 아니며, 현재 대안 설정은 hardened upstream에 필요한 internal token을 주입하지 않는다. Nginx baseline은 auth_request, 401 처리, header 추출과 덮어쓰기를 한 파일에서 관찰하기 쉽다는 학습상 이유가 있다.

AP4가 수용한 비용은 proxy session과 identity-header 신뢰 경계가 핵심 인프라가 된다는 점이다. App과 oauth2-proxy의 host port 비공개, 정확 일치 internal auth location, client header overwrite, 단일 trusted proxy IP, upstream internal-token 검증이 현재 가드레일이다. 운영에서는 shared secret을 secret manager에서 주입하고 rotation하거나 mTLS·workload identity로 강화해야 한다. 현재 fixture는 user와 email만 전달한다. Role이나 추가 claim이 필요하면 별도의 allowlist, 직렬화 규칙, 크기 제한, upstream 검증 계약을 설계해야 한다.

외부 브라우저 zone과 Nginx, oauth2-proxy, Spring upstream이 있는 AP4 deployment path를 나눈 edge trust 아키텍처.

Diagram description

왼쪽 외부 브라우저가 AP4_SESSION과 함께 AP4 deployment path의 공개 Nginx entry point를 호출한다. 같은 deployment path에서 Nginx는 host 비공개 oauth2-proxy의 internal /oauth2/auth endpoint에 subrequest를 보내 session을 검증하고 user와 email 결과를 받는다. 이어서 client가 보낸 동명 header를 덮어쓰고 Nginx-owned identity header와 internal token을 host 비공개 Spring upstream의 /edge/me로 전달한다. Upstream은 user header와 internal token을 함께 확인하며 JWT를 직접 입력으로 받지 않는다.

Editable source · Grounded VizSpec

선택이 코드와 흐름에 반영되는 방식

추적 규칙: 요청 한 번을 네 칸으로 기록한다

각 패턴의 worked example은 다음 네 칸을 반복한다.

  1. 입력: endpoint, method, query, cookie, header, body
  2. 변환: 실제 handler, configuration 또는 framework integration이 입력을 어떤 객체와 credential로 바꾸는가
  3. 출력: HTTP response 또는 다음 계층에 전달되는 object·header
  4. 다음 홉: 그 출력을 다음에는 누가 입력으로 받는가

동적 값은 <authorization-code>, <access-token>, <session-id>처럼 표시한다. 테스트가 전체 payload를 snapshot하지 않은 곳에서는 대표적인 모양만 제시하며, 일반적인 OAuth 구현에서 흔히 보인다는 이유로 검증하지 않은 field를 추가하지 않는다.

AP1 완주: callback code가 브라우저 Bearer 요청이 되기까지

1단계 — SPA를 열고 OAuth transaction을 시작한다

초기 입력은 다음 navigation이다.

GET http://localhost:8088/

Frontend Nginx는 SPA shell을 반환한다. 별도의 실제 callback.html 파일은 없지만, 존재하지 않는 경로를 index.html로 fallback하는 설정 때문에 /callback.html도 같은 shell을 연다. JavaScript module은 UserManager를 만들면서 다음 값을 고정한다.

authority          = http://localhost:8080/realms/keycloak-patterns
client_id          = spa-public
redirect_uri       = http://localhost:8088/callback.html
post_logout_uri    = http://localhost:8088/
response_type      = code
scope              = openid profile email
userStore          = InMemoryWebStorage
stateStore         = sessionStorage
automaticSilentRenew = true

userStorestateStore를 구분해야 한다. 전자는 로그인 뒤 User와 token set을 보관하는 곳이고 후자는 redirect를 건너야 하는 authorization transaction을 보관하는 곳이다. AP1은 User를 memory에 두고, state와 PKCE verifier는 Session Storage를 이용해 Keycloak 왕복을 건넌다.

사용자가 #login을 누르면 local handler가 인자를 조립해 token endpoint를 직접 부르는 것이 아니라 userManager.signinRedirect()를 호출한다. oidc-client-ts가 authorization URL을 만든다. Effective request의 핵심 모양은 다음과 같다.

GET http://localhost:8080/realms/keycloak-patterns/protocol/openid-connect/auth
  ?client_id=spa-public
  &redirect_uri=http%3A%2F%2Flocalhost%3A8088%2Fcallback.html
  &response_type=code
  &scope=openid%20profile%20email
  &state=<opaque-state>
  &code_challenge=<opaque-challenge>
  &code_challenge_method=S256

여기서 browser의 출력은 Keycloak로 향하는 full-page navigation이다. state와 challenge 값은 요청마다 달라진다. 커밋된 browser test가 직접 확인하도록 정의한 query는 response_type=code, code_challenge_method=S256, 비어 있지 않은 code_challenge다.

AP1에는 createPkcePair()라는 수동 helper도 있다. 이 함수는 32 random bytes를 padding 없는 Base64URL verifier로 바꾸고, SHA-256을 적용한 challenge와 "S256"을 반환한다. 그러나 실제 signinRedirect()가 이 helper를 호출하지는 않는다. Helper는 UI의 PKCE demo button에서 길이를 보여 주기 위한 코드이고 실제 로그인은 pinned oidc-client-ts가 수행한다. 따라서 demo에서 나온 43자 verifier를 실제 library token request의 정확한 verifier 길이라고 설명해서는 안 된다.

2단계 — callback 입력을 token set으로 바꾼다

Keycloak에서 사용자가 인증되면 브라우저는 다음과 같은 callback을 받는다.

GET http://localhost:8088/callback.html
  ?code=<authorization-code>
  &state=<opaque-state>

SPA는 path가 /callback.html이고 query에 code 또는 error가 있을 때 callback 경로로 판단한다. finishSigninCallback()userManager.signinRedirectCallback()을 호출하고, library가 저장했던 transaction state와 callback state를 대조한다. 성공 경로에서 browser가 보내는 token request의 의도는 다음과 같다.

POST http://localhost:8080/realms/keycloak-patterns/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&client_id=spa-public
&code=<authorization-code>
&redirect_uri=http://localhost:8088/callback.html
&code_verifier=<original-verifier>

spa-public은 secret이 없는 public client다. Keycloak 등록은 standard flow만 켜고 implicit flow와 direct grant를 끄며 S256을 요구한다. SPA는 /callback.html을 사용하지만 local realm의 redirect allowlist는 http://localhost:8088/*http://127.0.0.1:8088/* wildcard다. 따라서 exact callback만 허용하는 운영 가드레일이나 invalid redirect negative test까지 현재 fixture가 입증하는 것은 아니다. Token endpoint의 출력에서 현재 browser test가 관측하도록 정의한 것은 비어 있지 않은 access_token, refresh_token, id_token이다. expires_in 같은 일반적인 추가 field의 exact response를 이 문서의 계약으로 고정하지 않는다.

이 단계의 중요한 evidence boundary가 있다. Test는 authorization request의 challenge와 token request endpoint, grant_type=authorization_code를 관찰한다. 하지만 실제 code_verifier 값, client_id, redirect_uri, code 값 전체를 token request body에서 하나씩 assert하지는 않는다. 구현과 문서가 의도하는 PKCE sequence와 테스트가 직접 포착한 field를 구분해야 한다.

Library는 응답을 User로 만든다. 애플리케이션이 실제로 읽는 논리적 데이터는 다음과 같다.

User
├─ profile.sub
├─ profile.preferred_username
├─ access_token
├─ refresh_token
├─ id_token
├─ expires_at
└─ expired

Serialized user는 InMemoryWebStorage에 있고 module 변수 currentUser도 같은 live user를 가리킨다. Callback이 끝나면 SPA는 history.replaceState(..., "/")로 code와 state query를 주소창에서 제거한다. Token 원문을 화면에 표시하지 않고 다음 파생 metadata만 렌더한다.

{
  "subject": "<keycloak-sub>",
  "username": "regular-user",
  "expiresAt": "<ISO-8601-instant>",
  "accessTokenHeldBy": "browser memory",
  "refreshTokenHeldBy": "browser memory"
}

이 시점의 최종 browser 상태를 정확히 말하면 다음과 같다.

위치 남는 데이터 reload 뒤
JavaScript memory User, access·refresh·ID token, expiry, profile 사라짐
Session Storage redirect transaction용 state와 verifier callback 완료 뒤 제거되는 것이 계약
Local Storage 애플리케이션이 쓰지 않음 해당 없음
Keycloak origin cookie IdP SSO 상태가 존재할 수 있음 AP1 app memory와 별개

Memory user가 사라진다고 Keycloak SSO까지 로그아웃되는 것은 아니다. Reload 뒤 애플리케이션 token 상태를 포기했다는 말과 IdP session을 제거했다는 말은 구분해야 한다.

3단계 — JavaScript가 access token을 API input으로 바꾼다

사용자가 #call-api를 누르면 callProtectedApi()가 실행된다. currentUser가 없거나 expired이면 network request를 만들지 않고 다음 local UI error를 출력한다.

{"error":"로그인이 필요합니다."}

유효한 user라면 애플리케이션 코드가 명시하는 핵심 request shape는 다음과 같다.

GET http://localhost:8081/api/me
Authorization: Bearer <access-token>

이 URL은 frontend와 origin이 다르며 Authorization header를 사용한다. Browser의 direct API call을 성립시키기 위해 Spring CORS allowlist에는 frontend origin인 localhost:8088127.0.0.1:8088, GET·OPTIONS, Authorization·Content-Type만 둔다. 허용 목록 밖의 browser cross-origin 요청은 CORS 검사를 통과하지 못한다. 이는 browser-origin 경계이지 API의 network-level 접근 통제는 아니다. Browser standard상 preflight가 생기는 경로지만 커밋된 E2E는 preflight response를 별도로 assert하지 않고 최종 200을 확인하도록 작성되어 있다.

구현에는 한 가지 헷갈리기 쉬운 차이가 있다. Frontend Nginx에도 /api/ proxy가 있지만 SPA는 상대 URL /api/me가 아니라 absolute http://localhost:8081/api/me를 사용한다. 따라서 현재 happy path는 Nginx proxy가 아니라 browser가 host에 공개된 Resource Server를 직접 호출한다.

Spring 쪽 입력은 raw Bearer string이다. 요청마다 Bearer JWT로 인증하고 application session을 만들지 않기 위해 SecurityConfig.apiSecurity()는 CORS를 켜고 CSRF를 끄며 SessionCreationPolicy.STATELESS를 선택한다. 그 대가로 이미 발급된 self-contained JWT를 logout 순간에 server session처럼 즉시 없앨 수 없으며 짧은 TTL과 validator가 가드레일이 된다. Spring OAuth2 Resource Server가 header를 추출하고 JWT authentication provider를 거쳐 configured decoder를 호출한다. Repository code가 Spring 내부 filter를 직접 생성하지는 않으므로, 이 흐름은 DSL이 설치하는 framework integration과 custom bean 경계를 나눠 읽어야 한다.

Custom code의 변환 순서는 다음과 같다.

raw Bearer JWT
  → NimbusJwtDecoder(JWK signature)
  → default issuer + timestamp validators
  → AudienceValidator("keycloak-pattern-api")
  → validated Jwt
  → KeycloakRealmRoleConverter
  → authenticated principal + ROLE_* authorities

외부 issuer와 내부 JWK URL도 구분된다. Expected issuer는 token 안의 browser-visible 값인 http://localhost:8080/realms/keycloak-patterns다. 공개키를 가져오는 JWK URL은 container network의 http://keycloak:8080/.../certs다. 같은 realm을 가리키지만 하나는 claim 검증 기준이고 하나는 network access 경로다.

AudienceValidatorjwt.getAudience()keycloak-pattern-api가 포함됐는지 확인한다. 누락되면 invalid_token 결과를 만든다. KeycloakRealmRoleConverterrealm_access.roles의 string을 골라 ROLE_ prefix를 붙인다. 예를 들어 user-roleROLE_user-role이 된다.

그러나 이 worked example의 /api/me는 특정 role을 요구하지 않고 .authenticated()만 요구한다. Role claim이 없어서 converter 결과가 빈 list여도 JWT가 유효하면 /api/me 자체는 통과할 수 있다. admin-role의 효과는 별도 /api/admin endpoint에서 나타난다. Regular user는 403, admin user는 200을 기대하는 별도 acceptance contract가 있다.

마지막으로 ApiController.currentUser(Jwt)가 verified JWT를 reader-facing JSON으로 투영한다.

{
  "subject": "<keycloak-user-sub>",
  "username": "regular-user",
  "issuer": "http://localhost:8080/realms/keycloak-patterns",
  "audience": ["<possibly-other-audiences>", "keycloak-pattern-api"]
}

Controller output에는 정확히 subject, username, issuer, audience 네 field가 있다. Subject의 실제 UUID와 audience 배열 전체는 동적이다. 현재 browser E2E는 UI의 httpStatus: 200과 decoded access token의 expected audience 포함만 확인하도록 작성되어 있다. username은 controller code와 synthetic MockMvc contract에 나타나지만 live AP1 E2E가 직접 assert하지 않는다.

SPA는 이 JSON을 다시 화면용 object로 조립한다.

{
  "httpStatus": 200,
  "resourceServerResponse": {
    "subject": "<keycloak-user-sub>",
    "username": "regular-user",
    "issuer": "http://localhost:8080/realms/keycloak-patterns",
    "audience": ["<possibly-other-audiences>", "keycloak-pattern-api"]
  },
  "tokenBoundary": {
    "subject": "<keycloak-user-sub>",
    "username": "regular-user",
    "expiresAt": "<ISO-8601-instant>",
    "accessTokenHeldBy": "browser memory",
    "refreshTokenHeldBy": "browser memory"
  }
}

한 요청 동안 data model은 token response → oidc-client-ts User → Authorization header → validated Jwt → controller Map → UI wrapper 순서로 바뀐다. AP1의 핵심은 그 가운데 access token 원문이 browser memory와 network header 양쪽을 지난다는 점이다.

4단계 — 실패와 수명주기를 같은 흐름에서 읽는다

입력 또는 사건 최초 거부 지점 관측 가능한 결과 보장하지 않는 세부
Bearer 없음 Spring Security /api/me 401 exact error body
잘못된 audience custom audience validator 401 UI용 JSON error 모양
잘못된 issuer issuer validator 401 UI용 JSON error 모양
regular user가 /api/admin 호출 authority decision 403 공통 error envelope
callback query의 error oidc-client-ts callback, app catch unauthenticated UI와 error message exact provider error schema
app memory user 없음 또는 expired callProtectedApi() local guard network call 없이 login-required JSON 자동 재로그인

SPA는 non-2xx 응답에서도 response.ok을 확인하기 전에 response.json()을 시도한다. Spring의 401 body가 비어 있거나 JSON이 아니면 의도한 “보호 API가 401을 반환했다”는 message보다 JSON parse error가 먼저 보일 수 있다. Negative E2E는 UI button 경로가 아니라 별도 Node fetch로 status만 확인하므로 이 failure UX는 현재 고정되어 있지 않다.

Refresh와 logout도 서로 다른 효과를 가진다. Realm은 access token 수명을 300초로 두고 refresh token rotation과 reuse 0을 사용한다. 커밋된 E2E는 refresh token을 직접 사용해 새 refresh token을 받고 이전 token이 거부되는지 확인하도록 정의한다. Revocation 뒤 refresh는 실패해야 하지만, 이미 발급된 self-contained access JWT는 expiry 전까지 API에서 계속 유효할 수 있다. Logout은 Keycloak SSO 종료와 app user 제거를 다루고, access JWT 즉시 deny-list와 같은 효과를 보장하지 않는다.

automaticSilentRenew=true도 구성되어 있지만, browser가 실제 expiry를 기다려 silent renewal을 완료하고 새 User를 memory에 저장하는 경로는 acceptance test가 아니다. Manual refresh helper로 검증하는 것과 app runtime의 automatic renewal을 같은 결과로 간주하지 않는다.

브라우저 SPA, Keycloak, Resource Server 사이에서 authorization request, callback, token 교환, Bearer API 호출과 JSON 응답이 이어지는 순서도.

Diagram description

브라우저 SPA가 S256 code challenge가 포함된 authorization request를 Keycloak에 보낸다. Keycloak이 code와 state를 callback으로 돌려주면 SPA는 원래 verifier를 포함해 token endpoint에 code를 제출하고 access, refresh, ID token을 받는다. 이어서 SPA가 access token을 Authorization Bearer header에 넣어 Resource Server의 /api/me를 직접 호출하고 사용자 JSON을 받는다.

Editable source · Grounded VizSpec

AP2 완주: server의 authorized client가 browser Bearer가 되기까지

1단계 — public UI에서 confidential login을 시작한다

초기 입력은 다음과 같다.

GET http://localhost:8082/

/, /index.html, /app.js는 인증 없이 열린다. 사용자가 login button을 누르면 JavaScript는 다음 navigation만 수행한다.

window.location.assign("/oauth2/authorization/keycloak");

/oauth2/authorization/keycloak은 애플리케이션 controller가 아니라 Spring Security의 OAuth client endpoint다. Registration keycloak은 다음 값을 제공한다.

client_id              = token-mediating-confidential
client_authentication  = client_secret_basic
grant_type             = authorization_code
scopes                 = openid profile email
callback               = http://localhost:8082/login/oauth2/code/keycloak
authorization_uri      = http://localhost:8080/.../auth
token_uri              = http://keycloak:8080/.../token
principal claim        = preferred_username

Browser는 Keycloak login page로 redirect되고 regular-user credentials를 제출한다. Keycloak client 등록은 confidential, standard flow enabled, implicit와 direct grant disabled, exact callback으로 구성된다.

여기서 AP1·AP3·AP4와 억지로 대칭을 만들면 안 된다. AP2 client 설정에는 S256을 강제하는 속성이 없고 AP2 E2E도 authorization request의 challenge를 검사하지 않는다. AP2는 Authorization Code confidential client라는 사실까지는 분명하지만, 현재 구현을 PKCE S256 검증 예시라고 설명할 근거는 없다.

Login을 시작할 때 Spring Security는 authorization request와 state를 HttpSession에 저장하고 browser에 그 transaction을 찾는 AP2_SESSION을 발급한다. 이 cookie는 token 교환이 끝난 뒤에 처음 생기는 것이 아니다. Keycloak redirect를 건너 callback의 state를 원래 transaction과 연결하기 위해 먼저 사용된다.

2단계 — callback을 session과 authorized client로 바꾼다

성공 뒤 browser input은 다음 형태다.

GET http://localhost:8082/login/oauth2/code/keycloak
  ?code=<authorization-code>
  &state=<opaque-state>
Cookie: AP2_SESSION=<opaque-session-id>

Spring oauth2Login이 session에서 authorization transaction을 복원하고 callback state를 대조한 뒤 code를 처리한다. Mediator는 server network에서 Keycloak token endpoint를 호출하며 client_secret_basic으로 자기 client를 인증한다. On-wire 의미상 client ID와 secret은 HTTP Basic client authentication에 사용되고 code, redirect URI와 grant type은 token request에 들어간다. 현재 E2E는 실제 token request header와 body 전체를 캡처하지 않으므로 exact serialization까지 계약으로 삼지는 않는다.

교환이 성공하면 기존 session transaction은 authenticated SecurityContext로 이어지고, 별도 authorized-client state에 token이 저장된다.

AP2_SESSION
  → servlet HttpSession의 login SecurityContext
  → Authentication(principal name = preferred_username)

("keycloak", principal name)
  → OAuth2AuthorizedClientService
  → access token + refresh token

Application은 OAuth2AuthorizedClientService 구현을 직접 선언하지 않는다. 현재 Spring Boot 자동구성이 선택하는 것은 in-memory service이고, Spring Session·Redis·JDBC token store 의존성도 없다. 따라서 AP2_SESSION으로 찾는 login state와 principal·registration으로 찾는 token state가 모두 process-local memory에 의존한다.

Browser가 계속 제시하는 application credential은 OAuth token 값이 아니라 AP2_SESSION=<opaque-session-id> cookie다. 이 cookie는 authorization transaction 때부터 사용되고 성공 뒤 login SecurityContext를 찾는다. 설정은 HttpOnly와 SameSite=Lax를 명시한다. Cookie가 token map 자체를 직렬화한다고 설명해서는 안 된다. Actual access·refresh token은 별도 authorized-client service에 있다. 인증 시 session ID rotation이나 전체 Set-Cookie timing은 현재 E2E가 고정하지 않는다.

defaultSuccessUrl("/", true) 때문에 성공 뒤 browser는 root로 돌아온다. Callback의 exact 302 chain과 실패 body는 test가 고정하지 않는다.

3단계 — /token/boundary가 server custody를 boolean으로 투영한다

로그인 뒤 사용자가 “token boundary” 버튼을 누르면 JavaScript가 다음 요청을 보낸다.

GET http://localhost:8082/token/boundary
Accept: application/json
Cookie: AP2_SESSION=<opaque-session-id>

Spring Security가 session에서 Authentication을 복원한 뒤 TokenBoundaryController.tokenBoundary()가 호출된다. Controller는 다음 key로 server store를 조회한다.

client registration id = "keycloak"
principal name         = authentication.getName()

Local user configuration에서는 principal name이 preferred_username이므로 정상 예시는 regular-user다. Authorized client 객체와 그 안의 access·refresh token 존재 여부를 boolean으로 바꾼다. Token 원문은 읽어서 응답에 넣지 않는다.

정상 output은 다음 다섯 field다.

HTTP/1.1 200 OK
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json
{
  "pattern": "AP2-token-mediating-backend",
  "principal": "regular-user",
  "accessTokenStored": true,
  "refreshTokenStored": true,
  "browserReceivesRefreshToken": false
}

이 endpoint는 진단용 projection이다. 인증된 session은 있지만 authorized client가 없다면 access·refresh boolean이 false인 200 응답을 만든다. “Token이 없으면 항상 401”이라고 설명하면 다음 endpoint와 혼동한다.

4단계 — /token/access가 server object를 raw token JSON으로 바꾼다

API 호출 button은 먼저 다음 입력을 만든다.

GET http://localhost:8082/token/access
Accept: application/json
Cookie: AP2_SESSION=<opaque-session-id>

AccessTokenController.accessToken(Authentication)의 변환은 구체적이다.

  1. OAuth2AuthorizeRequest.withClientRegistrationId("keycloak")를 시작한다.
  2. 현재 Authentication을 principal로 넣는다.
  3. OAuth2AuthorizedClientManager.authorize(request)를 호출한다.
  4. 반환된 authorized client에서 access token을 꺼낸다.
  5. 원문 token, type, expiry만 JSON으로 만든다.

Manager에는 authorization-code와 refresh-token provider가 구성되어 있다. 따라서 만료 상황에서 refresh를 시도할 수 있는 integration point는 있다. 그러나 access token 만료를 기다려 실제 refresh 성공과 rotated token 저장을 확인하는 E2E는 없다.

성공 output의 key 집합은 정확히 세 개다.

HTTP/1.1 200 OK
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json
{
  "access_token": "<raw-keycloak-jwt>",
  "token_type": "Bearer",
  "expires_at": "<ISO-8601-instant>"
}

refresh_token은 없다. 하지만 access token은 분명히 HTTP response body에 있다. Authorized client나 access token이 없으면 controller가 다음 실패를 만든다.

HTTP/1.1 401 Unauthorized

Reason은 No authorized Keycloak client is available이지만 Spring의 exact error body 모양은 별도 handler나 test로 고정되지 않았다.

이 endpoint에는 handoff ID, nonce, consume flag, 사용 후 delete, 재호출 거부가 없다. 같은 authenticated session은 현재 access token을 다시 요청할 수 있다. 그러므로 data flow는 다음처럼 써야 한다.

repeatable GET
  → current authorized client lookup/refresh opportunity
  → current raw access token response

“한 번만 교환 가능한 code”라고 바꾸어 말하면 안 된다.

5단계 — browser가 access JSON을 Resource Server input으로 재조립한다

JavaScript는 response를 지역 변수로 구조 분해한다.

const {
  access_token: accessToken,
  expires_at: expiresAt
} = await tokenResponse.json();

그 값을 Web Storage나 cookie에 쓰지 않고 바로 다음 요청 header로 넣는다.

GET http://localhost:8081/api/me
Accept: application/json
Authorization: Bearer <raw-keycloak-jwt>
Origin: http://localhost:8082

Raw access token은 짧은 시간이라도 세 경계를 지난다.

/token/access response body
  → JavaScript local variable
  → /api/me Authorization header

“Memory-only”는 persistent storage에 쓰지 않는다는 뜻이다. 실행 중 script가 response나 local variable을 읽을 수 없다는 뜻은 아니다.

Resource Server는 AP1과 같은 JWT validation chain을 사용한다. Session은 stateless이고 issuer, timestamp, JWK signature, keycloak-pattern-api audience를 검증한다. AP2 browser의 direct Bearer 호출만 열기 위해 CORS allowlist는 AP2 UI origin과 /api/**GET·OPTIONS, Authorization·Content-Type으로 좁힌다. 허용 목록 밖의 browser cross-origin 요청은 CORS 검사를 통과하지 못한다. 이는 browser-origin 경계이지 API의 network-level 접근 통제는 아니다.

ApiController.currentUser()의 output도 네 field다.

{
  "subject": "<keycloak-user-sub>",
  "username": "regular-user",
  "issuer": "http://localhost:8080/realms/keycloak-patterns",
  "audience": ["<possibly-other-audiences>", "keycloak-pattern-api"]
}

현재 E2E는 status 200, username, expected audience 포함을 확인하도록 정의한다. SPA가 화면에 렌더하는 최종 object는 token 원문을 다시 노출하지 않고 boundary를 요약한다.

{
  "accessTokenHeldInMemoryOnly": true,
  "refreshTokenReceived": false,
  "accessTokenExpiresAt": "<ISO-8601-instant>",
  "resourceApiStatus": 200,
  "resource": {
    "subject": "<keycloak-user-sub>",
    "username": "regular-user",
    "issuer": "http://localhost:8080/realms/keycloak-patterns",
    "audience": ["<possibly-other-audiences>", "keycloak-pattern-api"]
  }
}

AP2 전체 변환을 한 줄로 압축하면 다음과 같다.

authorization code
  → Spring oauth2Login
  → in-memory OAuth2AuthorizedClient(access + refresh)
  → /token/access(access only)
  → JavaScript local variable
  → browser-created Bearer header
  → validated Jwt
  → /api/me JSON

6단계 — AP2의 실패와 공백을 endpoint별로 구분한다

상황 현재 경계의 결과 확인된 것 아직 고정되지 않은 것
미인증 /token/boundary 또는 /token/access controller 이전 login entry point UI는 redirect와 401 양쪽을 처리 exact redirect/401 contract
인증됨, boundary 조회에 authorized client 없음 boolean false를 담은 200 controller branch token 복구 UX
인증됨, access endpoint에 client/token 없음 401 controller status와 reason exact JSON error body
anonymous /api/me 401 backend test contract error envelope
foreign audience invalid_token validation result validator test contract AP2 browser E2E의 401
access token expiry manager가 refresh 가능한 provider를 가짐 configuration real refresh success·failure
mediator restart 또는 replica 이동 process-local state에 영향 구현상 저장소 경계 recovery/failover contract

AP2는 refresh credential을 browser 밖으로 옮긴다. 하지만 logout 시 session과 authorized client를 함께 삭제하는 code, token-at-rest encryption, shared durable store, handoff replay rejection은 구현되어 있지 않다. 이 공백은 access-only 경계를 부정하지 않지만 운영 완성도를 과장하지 못하게 한다.

브라우저, Spring mediator, authorized-client store, Resource Server 사이에서 AP2_SESSION 요청, access-only 응답, 브라우저 Bearer 호출과 JSON 응답이 이어지는 순서도.

Diagram description

브라우저가 AP2_SESSION cookie와 함께 /token/access를 Spring mediator에 요청한다. Mediator는 현재 principal과 keycloak registration으로 authorized-client store에서 token을 조회하고 access token, type, expiry만 응답한다. 브라우저는 access token을 지역 변수로 받아 Authorization Bearer header를 만들고 Resource Server의 /api/me를 직접 호출한 뒤 사용자 JSON을 받는다. Refresh token은 브라우저 응답에 포함되지 않는다.

Editable source · Grounded VizSpec

AP3 완주: session cookie가 BFF의 downstream Bearer가 되기까지

1단계 — BFF가 PKCE transaction과 confidential code 교환을 함께 소유한다

브라우저는 먼저 BFF가 제공하는 UI를 연다.

GET http://localhost:8083/

Login button의 local code는 AP2와 같은 모양이다.

window.location.assign("/oauth2/authorization/keycloak");

차이는 Spring Security 설정 안에 있다. SecurityConfig.bffSecurity()는 base URI /oauth2/authorizationDefaultOAuth2AuthorizationRequestResolver를 만들고 OAuth2AuthorizationRequestCustomizers.withPkce()를 장착한다. Framework resolver가 keycloak registration을 읽어 state와 verifier를 만들고 S256 challenge를 authorization request에 넣는다.

Effective browser request는 다음과 같은 모양이다.

GET http://localhost:8080/realms/keycloak-patterns/protocol/openid-connect/auth
  ?response_type=code
  &client_id=bff-confidential
  &redirect_uri=http%3A%2F%2Flocalhost%3A8083%2Flogin%2Foauth2%2Fcode%2Fkeycloak
  &scope=openid%20profile%20email
  &state=<opaque-state>
  &code_challenge=<opaque-challenge>
  &code_challenge_method=S256

AP3 E2E는 client ID, S256 method와 nonempty challenge를 확인하도록 작성되어 있다. Authorization request와 PKCE verifier는 Spring의 session-mediated OAuth login transaction에 속한다. Browser에는 그 session을 찾는 AP3_SESSION cookie가 생기지만 verifier나 client secret을 JavaScript 응답으로 주지는 않는다.

Keycloak 인증 뒤 callback input은 다음과 같다.

GET http://localhost:8083/login/oauth2/code/keycloak
  ?code=<authorization-code>
  &state=<opaque-state>
Cookie: AP3_SESSION=<opaque-session-id>

Spring OAuth login filter가 saved authorization request를 읽고 state를 대조한다. BFF는 server network에서 token endpoint에 grant_type=authorization_code, code, 동일 redirect URI와 verifier를 보낸다. Client authentication은 client_secret_basic이다. Token response의 access·refresh token은 OAuth2AuthorizedClientService에 저장된다. 검증된 ID token에서 구성된 OIDC principal은 Authentication이 되어 HttpSession의 SecurityContext에 연결된다.

이 단계에서 browser가 관측하는 출력은 root로 돌아가는 redirect와 AP3_SESSION이다.

Set-Cookie: AP3_SESSION=<opaque>; HttpOnly; SameSite=Lax
Location: /

Local YAML은 Secure, Domain과 만료를 별도로 고정하지 않는다. HTTP 학습 환경의 관측값을 운영 cookie 기본값처럼 일반화해서는 안 된다.

Server state를 더 정확히 펼치면 다음 관계다.

AP3_SESSION
  → HttpSession
  → SecurityContext
  → Authentication.getName()
  → ("keycloak", principal name)
  → OAuth2AuthorizedClientService
  → access token + refresh token

현재 store는 session ID마다 독립적인 token vault를 구현한 것이 아니라 registration과 principal name으로 authorized client를 찾는 application-level store다. 같은 principal이 여러 browser session에서 로그인할 때 entry를 공유하거나 덮어쓸 수 있는 운영 의미가 있다. Spring Session, Redis, JDBC repository, encrypted token store는 현재 구성에 없다.

2단계 — /bff/token-boundary는 token 값을 내보내지 않고 server state를 설명한다

브라우저 입력은 session cookie뿐이다.

GET http://localhost:8083/bff/token-boundary
Accept: application/json
Cookie: AP3_SESSION=<opaque-session-id>

Security filter가 Authentication을 복원한 뒤 BffController.tokenBoundary(Authentication)가 실행된다. Controller는 ("keycloak", authentication.getName())으로 OAuth2AuthorizedClientService를 직접 조회한다. 이 경로는 manager의 authorize()를 호출하지 않으므로 access token refresh를 수행하는 endpoint가 아니다. 객체와 token의 존재 여부만 boolean으로 바꾼다.

정상 output은 다음과 같다.

HTTP/1.1 200 OK
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json
{
  "pattern": "AP3-backend-for-frontend",
  "principal": "regular-user",
  "accessTokenStoredOnServer": true,
  "refreshTokenStoredOnServer": true,
  "browserTokenCount": 0,
  "csrfProtectionEnabled": true
}

browserTokenCount: 0은 browser를 runtime에서 검사해 계산한 수치가 아니라 controller가 넣는 literal이다. 이 field 하나가 token 비노출을 증명하지 않는다. Browser network에 token endpoint call과 Resource Server 직접 call이 없는지, Web Storage가 비었는지를 E2E contract가 별도로 확인하도록 작성된 이유다.

AP2 boundary와 마찬가지로 authorized client가 없어도 인증된 session이라면 token boolean이 false인 200을 만들 수 있다. Token 원문은 어느 경우에도 이 response에 직렬화하지 않는다.

3단계 — /bff/api/me가 session input을 downstream Bearer로 바꾼다

AP3 UI의 자신의 정보 조회는 다음 request 하나로 시작한다.

GET http://localhost:8083/bff/api/me
Accept: application/json
Cookie: AP3_SESSION=<opaque-session-id>

여기에 Authorization header는 없다. Browser code에는 access token local variable도 없다. 그다음 변환은 BffController.currentUser(Authentication) 안에서 일어난다.

  1. authorizedClient(authentication) helper를 호출한다.
  2. Helper는 registration ID "keycloak"과 현재 Authentication으로 OAuth2AuthorizeRequest를 만든다.
  3. OAuth2AuthorizedClientManager.authorize()를 호출한다.
  4. Manager는 현재 access token을 사용하거나, 만료됐고 refresh token이 있으면 server-to-server refresh를 시도할 수 있다.
  5. 유효한 access token을 controller로 돌려준다.

Manager bean은 AuthorizedClientServiceOAuth2AuthorizedClientManager이고 authorization-code와 refresh-token provider를 함께 사용한다. 이 경로가 AP3의 token lifecycle owner가 BFF라는 사실을 코드로 드러낸다.

Authorized client나 access token이 없으면 helper가 다음 local failure를 만든다.

HTTP/1.1 401 Unauthorized

Reason은 No authorized Keycloak client is available이다. 성공하면 BFF의 RestClient가 별도의 downstream input을 조립한다.

GET http://app:8081/api/me
Authorization: Bearer <server-held-access-token>

Browser가 보낸 AP3_SESSION은 downstream으로 전달되지 않는다. BFF가 session을 application credential로 소비하고, Resource Server가 이해하는 Bearer credential로 바꾼다. Resource Server는 AP1·AP2와 같은 stateless JWT path에서 signature, issuer, timestamp와 keycloak-pattern-api audience를 검증한다.

ApiController.currentUser(Jwt)가 만드는 downstream output은 다음 네 field다.

{
  "subject": "<keycloak-user-sub>",
  "username": "regular-user",
  "issuer": "http://localhost:8080/realms/keycloak-patterns",
  "audience": ["<possibly-other-audiences>", "keycloak-pattern-api"]
}

BFF는 ResponseEntity<Map<String, Object>>를 받아 그대로 controller return value로 사용한다. UI helper는 HTTP status를 화면용 object에 더해 렌더한다. 한 번의 요청을 model 변화로만 보면 다음과 같다.

AP3_SESSION
  → HttpSession SecurityContext
  → Authentication
  → OAuth2AuthorizeRequest
  → OAuth2AuthorizedClient
  → Bearer header
  → validated Jwt
  → Resource Server Map
  → BFF ResponseEntity
  → browser JSON

이 흐름에는 중요한 network gap이 있다. Compose는 학습 편의를 위해 Resource Server의 8081을 host에도 publish한다. E2E는 AP3 UI가 8081을 직접 호출하지 않는다는 것을 확인하도록 정의하지만, network상 모든 client가 BFF만 거치도록 강제했다는 증거는 아니다. 운영에서 BFF-only topology를 원한다면 Resource Server를 private network에 두어 직접 경로를 닫아야 한다.

Downstream failure도 과장하면 안 된다. Resource Server가 invalid audience, expired token 등으로 401을 반환할 수 있지만 BFF의 RestClient.retrieve() 뒤에 status mapping contract가 없다. 그래서 “downstream 401을 BFF가 exact 401 body로 그대로 전달한다”고 보장할 수 없다. Timeout, retry, circuit breaker, relogin 변환도 구현되어 있지 않다.

4단계 — CSRF 발급에서 masked body와 raw cookie를 구분한다

Cookie session은 browser가 요청마다 자동 첨부한다. 따라서 GET /bff/api/me만으로는 상태 변경 보호를 설명할 수 없다. AP3는 preference 변경을 별도 worked example로 둔다.

먼저 browser가 CSRF material을 요청한다.

GET http://localhost:8083/bff/csrf
Accept: application/json
Cookie: AP3_SESSION=<opaque-session-id>

CookieCsrfTokenRepository.withHttpOnlyFalse()는 JavaScript가 읽을 수 있는 기본 XSRF-TOKEN cookie를 path /에 만든다. CsrfController.csrf(CsrfToken)는 request attribute의 token을 materialize하고 다음 JSON을 반환한다.

HTTP/1.1 200 OK
Cache-Control: no-store
Pragma: no-cache
Set-Cookie: XSRF-TOKEN=<raw-csrf-token>; Path=/
{
  "headerName": "X-XSRF-TOKEN",
  "parameterName": "_csrf",
  "token": "<xor-masked-csrf-token>"
}

Body의 token과 cookie의 값은 같은 문자열이 아니다. XorCsrfTokenRequestAttributeHandler가 request attribute용 token을 XOR와 Base64로 mask하기 때문에 controller JSON에는 masked 값이 보인다. Cookie repository의 XSRF-TOKEN에는 raw 값이 있다.

SPA도 JSON token을 POST에 쓰지 않는다. JSON에서는 headerName만 읽고, document.cookie에서 raw XSRF-TOKEN을 찾아 다음 header를 만든다.

body.token             = masked token
cookie XSRF-TOKEN      = raw token
POST X-XSRF-TOKEN      = same raw token

SpaCsrfTokenRequestHandler가 이 조합을 맞춘다. Request attribute 노출에는 XOR handler를 사용하지만 expected header가 존재하면 plain resolver로 submitted raw token을 읽는다. Header가 없으면 XOR resolver 경로를 사용한다.

이 구분을 놓치면 “CSRF JSON에서 받은 token을 그대로 header에 복사한다”는 잘못된 구현 설명이 된다. 실제 SPA의 data source는 cookie다.

BFF CSRF endpoint가 raw XSRF cookie와 masked JSON token으로 분기하고, SPA가 raw cookie만 실제 POST header 값으로 사용해 Spring CSRF filter에 제출하는 데이터 흐름.

Diagram description

왼쪽의 BFF CSRF endpoint에서 두 결과가 갈라진다. XSRF-TOKEN cookie에는 raw token이 저장되고 JSON body에는 XOR와 Base64로 masked된 token 및 headerName이 담긴다. 두 결과는 SPA의 POST 조립 단계로 모이지만, JSON에서는 headerName만 사용하고 실제 X-XSRF-TOKEN 값은 document.cookie에서 읽은 raw token이다. POST에는 같은 raw 값을 가진 cookie와 header가 함께 도달하고 Spring CSRF filter가 일치 여부를 확인한다.

Editable source · Grounded VizSpec

5단계 — form input이 process-global preference가 되기까지

정상 상태 변경 request는 다음과 같다.

POST http://localhost:8083/bff/api/preferences
Content-Type: application/x-www-form-urlencoded
Cookie: AP3_SESSION=<opaque-session-id>; XSRF-TOKEN=<raw-csrf-token>
X-XSRF-TOKEN: <same-raw-csrf-token>

theme=dark

Controller보다 먼저 Spring CSRF filter가 repository의 expected token과 submitted header를 비교한다. Header가 없거나 값이 맞지 않으면 controller는 실행되지 않고 403이 된다. Valid request는 @RequestParam(defaultValue = "system") String theme로 bind된다.

BffController.updatePreference()는 값을 AtomicReference<String>set()하고 다음 output을 만든다.

{
  "updated": true,
  "theme": "dark",
  "principal": "regular-user"
}

이어지는 GET /bff/api/preferences는 다음처럼 current value만 반환한다.

{"theme":"dark"}

여기서 AtomicReference를 사용자별 preference repository라고 오해하면 안 된다. Singleton controller 안의 reference 한 개이고 user나 session key가 없다. 한 사용자가 dark로 바꾸면 같은 process의 다른 사용자도 같은 값을 읽을 수 있다. Restart하면 기본 "system"으로 돌아간다. Atomic operation은 동시 get·set의 원자성만 제공하며 사용자 격리, input validation, persistence, audit, authorization을 제공하지 않는다. theme도 enum이나 길이 검증 없이 arbitrary string으로 들어간다.

이 endpoint의 목적은 preference 기능을 완성하는 것이 아니라 cookie-authenticated state change에서 CSRF filter가 어느 시점에 작동하는지 보여 주는 데 있다.

6단계 — CSRF와 SameSite 실패를 별도 방어선으로 읽는다

입력 Cookie 동작 CSRF 동작 결과
same-origin, AP3 session, CSRF header 없음 session cookie 첨부 filter가 token 부재 거부 403
same-origin, matching raw cookie/header session cookie 첨부 token 일치 controller 200
다른 port지만 same-site인 요청, header 없음 session cookie가 실릴 수 있음 token 부재 거부 403
127.0.0.1에서 localhost로 cross-site POST SameSite=Lax로 AP3_SESSION이 request header에서 제외되는지 확인 이 test는 이후 server 처리를 고정하지 않음 최종 status/body가 아니라 cookie omission이 acceptance point

SameSite는 cookie의 cross-site 전송을 제한하는 browser 정책이고 CSRF token은 state-changing request의 의도를 server가 검증하는 application protocol이다. Port가 달라도 site 계산상 같은 경우가 있으므로 둘은 서로 대체할 수 없다.

JavaScript가 OAuth token을 받지 않는다고 XSS가 무해해지는 것도 아니다. Same-origin 악성 script는 피해자 session으로 BFF endpoint를 호출하고 readable XSRF cookie도 읽을 수 있다. AP3가 줄이는 것은 access·refresh token 원문이 browser script에서 유출되어 다른 client나 직접 API 호출에 재사용되는 반경이다. CSP, output encoding, dependency integrity와 application authorization은 여전히 별도 방어선이다.

브라우저, BFF, authorized-client store, Resource Server 사이에서 AP3_SESSION 요청, server-held token 조회, downstream Bearer 호출과 중계 JSON이 이어지는 순서도.

Diagram description

브라우저가 Authorization header 없이 AP3_SESSION cookie로 /bff/api/me를 호출한다. BFF는 현재 Authentication으로 authorized-client manager를 호출해 server-held access token을 얻고 Resource Server의 /api/me에 Bearer header를 붙인다. Resource Server가 JWT를 검증해 사용자 JSON을 반환하면 BFF가 ResponseEntity로 받아 브라우저에 중계한다. 브라우저 session cookie는 downstream으로 전달되지 않는다.

Editable source · Grounded VizSpec

AP4 완주: proxy session이 trusted identity JSON이 되기까지

1단계 — 미인증 navigation을 internal auth query로 바꾼다

외부에서 publish된 application entry point는 Nginx의 8088뿐이다. App의 8081과 oauth2-proxy의 4180은 Compose network에 expose되지만 host ports로 publish되지 않는다.

Cookie가 없는 최초 입력은 다음과 같다.

GET http://localhost:8088/

Nginx의 location /는 바로 upstream을 호출하지 않고 먼저 다음 directive를 실행한다.

auth_request /oauth2/auth;

location = /oauth2/authinternal이다. Nginx가 만드는 subrequest만 들어갈 수 있고 browser가 같은 URL을 직접 호출하면 정상 auth endpoint로 사용할 수 없다. Subrequest는 body를 보내지 않고 Content-Length를 비운다. 대신 원래 요청의 문맥을 header로 바꾼다.

Nginx가 만드는 auth input 값의 출처
X-Original-URL scheme, host와 original request URI
X-Real-IP client address
X-Forwarded-For proxy chain
X-Forwarded-Host original host
X-Forwarded-Proto original scheme
X-Forwarded-Uri original request URI
Cookie: AP4_SESSION=... browser에 cookie가 있을 때 원래 request

미인증 상태에서 oauth2-proxy의 auth endpoint가 401을 반환하면 general / location은 @oauth2_signin으로 이동해 다음 redirect를 만든다.

HTTP/1.1 302 Found
Location: http://localhost:8088/oauth2/start?rd=http://localhost:8088/

Browser가 /oauth2/start를 따라가면 Nginx의 /oauth2/ location이 oauth2-proxy로 proxy한다. oauth2-proxy는 Keycloak authorization endpoint로 redirect하며 핵심 query는 다음과 같다.

client_id=edge-proxy
redirect_uri=http://localhost:8088/oauth2/callback
scope=openid profile email
code_challenge=<opaque>
code_challenge_method=S256

현재 E2E는 unauthenticated root의 302, client ID, S256 method와 nonempty challenge를 확인하도록 작성되어 있다. Dynamic state나 전체 query ordering은 계약으로 고정하지 않는다.

2단계 — oauth2-proxy가 callback code를 proxy session으로 바꾼다

Keycloak 인증 뒤 browser input은 Nginx를 통해 oauth2-proxy로 전달된다.

GET http://localhost:8088/oauth2/callback
  ?code=<authorization-code>
  &state=<opaque-state>

/oauth2/ location이 request를 oauth2-proxy의 4180으로 보낸다. Token의 expected issuer는 browser-visible URL로 유지하면서 container가 실제 Keycloak service에 도달하도록 oauth2-proxy endpoint를 외부용과 내부용으로 분리한다. 그 대신 automatic discovery를 끄고 login·token·JWKS·userinfo URL을 각각 관리하는 비용을 수용한다.

issuer expected value = http://localhost:8080/realms/keycloak-patterns
login URL             = http://localhost:8080/.../auth
redeem/token URL      = http://keycloak:8080/.../token
JWKS/userinfo URL     = http://keycloak:8080/...

Browser가 도달해야 하는 URL은 localhost이고 container가 server-to-server로 도달해야 하는 URL은 service name keycloak이다. oauth2-proxy는 edge-proxy confidential client, client secret과 original verifier로 code를 교환한다. Browser request log에 Keycloak token endpoint가 나타나지 않아야 한다는 것이 acceptance contract다.

성공 뒤 browser에는 AP4_SESSION cookie가 남는다.

name       = AP4_SESSION
HttpOnly   = true
SameSite   = Lax
Secure     = false in local HTTP fixture
expire     = 1 hour in proxy configuration

별도 Redis 같은 server-side session store는 구성하지 않았다. session-cookie-minimal=true는 client-side session cookie에 access·refresh·ID token을 보관하지 않고 edge가 사용하는 최소 session 정보만 남긴다. 따라서 AP4에 지속적인 refresh-token custody가 있다고 주장할 근거도 없다. Browser 관점에서 이 cookie는 JavaScript가 읽지 못하고 다음 edge request에 자동 첨부되는 opaque credential이다. 운영 HTTPS에서는 Secure=true가 선행 조건이며, replica를 늘릴 때는 동일 cookie를 검증할 secret의 배포·rotation 계약이 필요하다.

3단계 — 인증된 /api/edge를 auth 결과와 upstream 요청으로 분해한다

로그인 뒤 browser가 보내는 example input은 다음과 같다.

GET http://localhost:8088/api/edge
Cookie: AP4_SESSION=<opaque-session>

공격자가 다음 header를 일부러 추가했다고 가정해도 된다.

X-Auth-Request-User: spoofed-admin
X-Auth-Request-Email: spoofed-admin@example.test
X-Internal-Auth-Token: attacker-controlled-token

Nginx는 먼저 같은 internal /oauth2/auth subrequest를 만든다. oauth2-proxy가 session을 유효하다고 판단하면 auth response에 X-Auth-Request-User, X-Auth-Request-Email과 갱신된 cookie가 있을 경우 Set-Cookie를 돌려준다. Nginx는 auth_request_set으로 이 값을 local variable에 복사한다.

$auth_user   ← oauth2-proxy X-Auth-Request-User
$auth_email  ← oauth2-proxy X-Auth-Request-Email
$auth_cookie ← oauth2-proxy Set-Cookie

그다음 original request를 그대로 전달하지 않는다. Exact external /api/edge는 internal upstream /edge/me로 다시 매핑된다.

GET http://app:8081/edge/me
X-Auth-Request-User: <oauth2-proxy-authenticated-user>
X-Auth-Request-Email: <oauth2-proxy-authenticated-email>
X-Internal-Auth-Token: <nginx-environment-secret>

Client가 보낸 세 header를 merge하지 않고 위 값으로 덮어쓴다. 따라서 공격자가 spoofed-admin을 보냈어도 upstream input은 oauth2-proxy가 확인한 실제 user가 된다.

General location /도 현재는 proxy_pass http://app:8081/edge/me를 사용한다. 즉 /orders/123 같은 arbitrary upstream path를 보존하는 범용 transparent reverse proxy가 아니다. Root와 /api/edge 예시를 동일 identity response로 연결해 auth-request와 header trust를 관찰하는 fixture다.

4단계 — controller가 edge header를 reader JSON으로 바꾼다

Spring EdgeIdentityController.currentUser(HttpServletRequest)/edge/me를 받는다. 변환 순서는 짧지만 신뢰 경계는 두 겹이다.

  1. X-Auth-Request-User를 읽고 blank인지 확인한다.
  2. X-Internal-Auth-Token을 읽는다.
  3. Configured token bytes와 supplied bytes를 MessageDigest.isEqual로 비교한다.
  4. 둘 다 유효하면 allowlisted identity field만 output Map에 넣는다.

정상 output은 다음 네 field다.

{
  "pattern": "AP4-edge-forward-auth",
  "user": "regular-user",
  "email": "regular-user@example.test",
  "identityHeader": "X-Auth-Request-User"
}

User header가 없거나 internal token이 없거나 틀리면 controller output은 다음과 같다.

HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
  "error": "trusted edge authentication is required"
}

이 검사는 Spring Security의 /edge/** rule이 수행하는 것이 아니다. 현재 SecurityConfig/edge/**permitAll로 두고 /edge/me controller가 직접 internal token을 확인한다. 새 edge endpoint를 추가하면서 같은 method를 호출하지 않으면 보호가 자동 상속되지 않는다. Production expansion에서는 filter, interceptor 또는 security chain처럼 모든 대상 endpoint에 적용되는 공통 경계로 옮겨야 한다.

AP4의 end-to-end model 변환은 다음과 같다.

AP4_SESSION cookie
  → internal auth subrequest
  → oauth2-proxy session result
  → X-Auth-Request-User / Email
  → nginx-owned allowlisted headers + internal token
  → HttpServletRequest headers
  → controller Map
  → browser identity JSON

AP1·AP2·AP3의 Resource Server는 JWT의 issuer와 audience를 직접 확인한다. AP4 /edge/me는 JWT를 입력으로 받지 않는다. 대신 edge를 거쳤다는 network topology와 internal-token check를 신뢰하고, edge가 투영한 user와 email만 사용한다.

5단계 — AP4의 401, 302와 404는 경로별로 다르다

외부 입력 인증 상태 최초 결정 지점 결과
GET / 미인증 general location의 auth 401 error page /oauth2/start로 302
GET /api/edge 미인증 exact API location의 auth 401 error page redirect 없는 401 {"error":"authentication required"}
GET /oauth2/auth 무관 internal exact location 외부에서는 404
GET / + spoofed identity headers 정상 AP4 session Nginx header overwrite 실제 authenticated user로 200
internal /edge/me + user header만 edge token 없음 controller 401 trusted-edge error
internal /edge/me + wrong token token mismatch controller 401 trusted-edge error

Redirect 없는 JSON 401은 정확히 /api/edge 예시 path에만 구성되어 있다. “AP4의 모든 API path가 JSON 401을 반환한다”고 일반화하면 안 된다. 다른 path는 현재 general location의 login redirect 규칙을 따른다.

App과 oauth2-proxy의 host port가 닫혀 있다는 사실도 중요하다. Controller의 shared token만으로는 외부 직접 접근이 어려워지는 network property를 대신할 수 없고, network isolation만으로는 내부 workload나 잘못된 proxy header가 신뢰되는 문제를 대신할 수 없다. 현재 예시는 둘을 함께 사용한다.

6단계 — identity projection의 범위를 인가로 오해하지 않는다

현재 edge response는 user와 email을 전달할 뿐 role, groups, tenant, authentication method, token expiry를 전달하지 않는다. AP4 패턴 자체가 추가 claim을 금지하는 것은 아니다. 다만 header를 늘릴 때마다 다음 계약이 필요하다.

  • oauth2-proxy 또는 별도 auth service가 claim을 어떤 source에서 읽는가
  • Nginx가 어떤 response header만 allowlist하는가
  • Client-supplied 동명 header를 항상 지우거나 덮어쓰는가
  • 다중 값, separator, escaping과 최대 크기는 무엇인가
  • Upstream이 header presence만 볼지 값과 internal service identity를 함께 검증할지
  • Role이 바뀌었을 때 proxy session과 downstream authorization이 언제 갱신되는가

AP4가 authentication gate를 중앙화했다고 application authorization까지 자동으로 완성되는 것은 아니다. 현재 /edge/me도 role decision을 하지 않는다.

브라우저, Nginx, oauth2-proxy, Spring upstream 사이에서 AP4_SESSION 검증, identity header 덮어쓰기, internal token 검증과 JSON 응답이 이어지는 순서도.

Diagram description

브라우저가 AP4_SESSION cookie로 Nginx의 /api/edge를 호출한다. Nginx는 oauth2-proxy의 internal auth endpoint에 subrequest를 보내고 인증된 user와 email 결과를 받는다. 이어서 client가 보낸 동명 header를 사용하지 않고 oauth2-proxy 결과와 Nginx 환경의 internal token으로 /edge/me 요청을 새로 조립한다. Spring controller가 user header와 internal token을 함께 확인해 identity JSON을 만들고 Nginx가 브라우저에 전달한다.

Editable source · Grounded VizSpec

Google login이 들어와도 네 애플리케이션 경계는 바뀌지 않는다

Google federation을 다섯 번째 애플리케이션 패턴으로 세면 두 protocol boundary를 섞게 된다. Google은 Keycloak 앞의 upstream identity provider다. 사용자가 Keycloak login page에서 Google을 선택하면 browser는 upstream authorization을 수행하고, Keycloak이 upstream response를 검증해 local identity와 연결한다.

그다음 애플리케이션으로 나가는 데이터는 다시 Keycloak이 만든다.

Google identity assertion
  → Keycloak broker validation
  → provider alias + upstream sub로 account identity 결정
  → Keycloak local user/session
  → Keycloak authorization code
  → AP1·AP2·AP3·AP4 중 선택한 downstream 경계

AP1 Resource Server가 신뢰하는 issuer도 Keycloak이고, AP2·AP3가 교환하는 code의 issuer도 Keycloak이며, AP4 oauth2-proxy가 연결하는 OIDC provider도 Keycloak이다. Upstream email이 같다는 이유만으로 application이 Google token을 직접 신뢰하거나 account를 자동 병합하지 않는다. Stable identity key는 provider와 upstream sub 조합이고, email 충돌은 기존 계정 소유권 증명 없이 자동 연결하지 않는 별도 account-linking 문제다.

현재 자동화는 controllable mock OIDC provider로 broker와 claim mapping 계약을 검증하도록 작성되어 있다. 실제 Google account, public HTTPS callback, consent와 production domain policy를 통과했다는 뜻은 아니다. Upstream IdP 검증 범위와 AP1AP4의 application credential 경계를 분리해야 이 사실 경계도 유지된다.

결정이 지켜지는지 확인하는 방법

테스트 개수보다 경계의 input과 output을 확인한다

“로그인이 성공한다”는 네 패턴 모두에서 너무 넓은 성공 기준이다. 로그인 뒤 browser에 refresh token이 노출돼도 화면은 열릴 수 있고, spoofed identity header가 통과해도 정상 사용자는 자기 이름을 볼 수 있다. 따라서 verification은 선택한 경계의 입력과 출력에 직접 연결되어야 한다.

아래 표는 최신 실행 성적표가 아니라 커밋된 자동 테스트가 확인하도록 정의한 acceptance contract다. Pattern별 verify flow는 stack을 다시 만들기 전에 Docker volume을 삭제하므로, 보존해야 할 local realm과 database가 있는 환경에서 그대로 실행해서는 안 된다.

패턴 테스트가 만드는 핵심 입력 기대 output 지키려는 경계
AP1 S256 authorization request, 실제 login, Bearer /api/me, 동일 정상 JWT를 expected issuer·audience가 다른 diagnostic server에 제출 정상 200, diagnostic server 401, runtime fetch hook에서 access token 관측, persistent Web Storage에 access token 없음 Browser가 token owner라는 사실과 Resource Server validation
AP2 Login session으로 boundary/access GET, 반환 token으로 direct API GET server access·refresh booleans true, refresh field 없음, access JSON 세 field, no-store, API 200 Refresh custody는 server, access credential은 browser
AP3 Session-only /bff/api/me, CSRF 없는 POST, matching header POST, cross-site POST browser token count 0, downstream JSON 200, 403/200 분리, SameSite cookie omission BFF token custody와 cookie-authenticated state-change protection
AP4 Cookie 없는 //api/edge, 정상 session, spoofed headers, external auth endpoint, direct app/proxy ports root 302, exact API 401, 실제 user 200, auth endpoint 404, internal ports inaccessible Edge만 trusted identity input을 만들 수 있는 path

AP1 검증을 단계별로 읽는 법

AP1 browser contract는 authorization request에서 response_type=code, S256 method와 challenge를 확인한다. Token request를 intercept해 authorization-code grant이고 access·refresh·ID token이 응답에 존재하는지 본다. 그다음 UI가 Resource Server를 직접 호출해 200을 받고, decoded access token의 audience에 keycloak-pattern-api가 있는지 확인한다.

이 test가 token 노출의 한계도 일부러 재현한다. Browser fetch를 hook한 뒤 API 호출에서 Bearer access token을 관측하도록 작성되어 있다. 동시에 Local Storage와 Session Storage에 access token substring이 남지 않는지 확인한다. 둘을 함께 봐야 “persistent storage에는 없지만 실행 중 JavaScript 경계에는 있다”는 설계가 검증된다.

Negative input은 wrong audience와 wrong issuer다. 두 diagnostic Resource Server가 같은 JWT를 401로 거부해야 한다. Invalid signature와 expired JWT를 전용 E2E로 넣는 계약은 없다. Unit test에서 synthetic JWT를 주입해 controller 200을 확인하는 것은 실제 Nimbus signature와 issuer validation을 통과했다는 증거도 아니다.

Refresh test는 새 refresh token 발급, 이전 refresh token 거부, revocation 뒤 refresh 거부를 확인하도록 정의한다. 이미 발급된 access token이 만료 전까지 200일 수 있다는 결과도 함께 본다. 자동 silent renewal, exact SSO cookie flags, CORS preflight와 callback error UX는 이 계약 밖이다.

성공 기준을 운영 문장으로 바꾸면 다음과 같다.

정상: challenge가 있고 code flow이며, API는 expected issuer와 audience JWT만 200
실패: wrong issuer/audience는 401, regular user의 admin endpoint는 403
노출 경계: token은 runtime JavaScript에서 보이지만 reload용 Web Storage 복사본은 없음

AP2 검증을 단계별로 읽는 법

AP2는 먼저 /token/boundary output의 세 boolean을 본다. Server에 access와 refresh token이 있고 browserReceivesRefreshToken은 false여야 한다. 그다음 /token/access response의 key가 access_token, expires_at, token_type 세 개뿐인지 확인하고 Cache-Controlno-store가 있는지 본다.

반환된 access JWT의 audience를 decode하고 browser가 Resource Server를 직접 호출해 200을 받는지도 확인하도록 작성되어 있다. Cookie는 AP2_SESSION, HttpOnly, SameSite=Lax여야 하고 Local Storage와 Session Storage에는 access token 원문이나 refresh_token 문자열이 없어야 한다.

이 acceptance contract가 입증하지 않는 것도 분명하다. /token/access를 두 번 불렀을 때 두 번째 요청이 거부되는지 확인하지 않으며 code에도 그 기능이 없다. Access expiry 뒤 실제 refresh, logout 뒤 session과 authorized-client 삭제, restart와 replica 이동, CORS 거부 origin은 검증하지 않는다.

AP2를 검토할 때는 다음 두 assertion을 별도로 유지해야 한다.

assertion A: refresh token은 browser response에 없다
assertion B: access token은 browser response와 Authorization header에 있다

A가 통과했다고 B까지 사라진 것으로 해석하면 AP2와 AP3의 경계를 혼동한다.

AP3 검증을 단계별로 읽는 법

AP3 authorization request는 bff-confidential client와 PKCE S256 challenge를 사용해야 한다. Callback은 BFF URI의 GET이고, browser request list에는 Keycloak token endpoint와 Resource Server 8081 direct request가 없어야 한다. AP3_SESSION은 HttpOnly·SameSite=Lax이고 browser Web Storage는 비어 있어야 한다.

/bff/token-boundary는 server access·refresh token booleans true, browserTokenCount: 0, csrfProtectionEnabled: true를 반환해야 한다. 앞서 설명했듯 browser count는 literal이므로 network와 storage assertion이 보완한다. /bff/api/me는 BFF URL에서 200을 받고 downstream response에 username과 expected audience가 있어야 한다.

State-changing path는 최소 세 요청으로 확인한다.

  1. GET /bff/csrf가 nonempty token metadata와 XSRF-TOKEN cookie를 만든다.
  2. Session cookie는 있지만 CSRF header가 없는 POST는 403이어야 한다.
  3. Raw cookie 값을 X-XSRF-TOKEN에 넣은 POST는 200과 theme: "dark"를 반환해야 한다.

별도의 cross-site request는 SameSite=Lax 때문에 AP3_SESSION이 전송되지 않는지 본다. Same-site이지만 origin이 다른 request에서는 cookie가 실릴 수 있으므로 CSRF header 부재로 403이 되어야 한다. 두 negative case가 서로 다른 방어선을 검증한다.

이 테스트는 preference의 사용자별 격리나 persistence를 검증하지 않는다. 실제 구현은 process-global AtomicReference 하나다. Shared session store, token encryption, logout, downstream failure mapping, timeout과 per-route authorization도 acceptance contract 밖이다.

AP4 검증을 단계별로 읽는 법

AP4는 미인증 browser navigation과 API request를 분리한다. Cookie 없는 root navigation은 302로 login을 시작해야 한다. Cookie 없는 exact /api/edge request는 Location header 없이 401이어야 한다. 이 두 assertion이 general browser UX와 programmatic API UX를 분리한다.

Authorization request는 edge-proxy와 PKCE S256 challenge를 포함해야 한다. Login 뒤 browser에는 HttpOnly·SameSite=Lax AP4_SESSION이 있어야 하고 browser network에 Keycloak token endpoint가 없어야 한다. Local Storage와 Session Storage가 비어 있고 document.cookie로 session cookie를 읽을 수 없어야 한다.

Spoofing test는 authenticated browser가 X-Auth-Request-User: spoofed-admin, fake email과 attacker-controlled internal token을 모두 보낸다. Response status는 200이지만 output user는 원래 authenticated user여야 하고 spoofed-admin이면 안 된다. 단순히 request가 실패하는지 보는 것이 아니라 Nginx가 client input을 overwrite하고 정상 identity를 보존하는지 확인한다.

마지막으로 외부 /oauth2/auth는 404, host의 4180과 8081은 접근 불가여야 한다. Backend unit contract는 missing user header, missing internal token과 wrong token이 모두 401이고 correct edge input은 200인지 확인한다.

남은 공백은 role propagation, new endpoint에 대한 centralized enforcement, state-changing upstream request의 CSRF, session renewal, replica sharing, internal secret rotation이다. Traefik 대안은 configuration을 load할 수 있는 수준이지 현재 hardened /edge/me를 같은 속성으로 통과시키는 end-to-end 대안이 아니다.

실제 runtime 검증을 수행할 때의 안전한 순서

현재 pattern별 verify procedure는 volume reset을 포함한다. 검증하려면 먼저 disposable environment인지 확인해야 한다.

사전 조건

  • 보존해야 할 Keycloak realm, user 또는 PostgreSQL data가 같은 Compose project에 없어야 한다.
  • 필요한 secret과 test user password는 environment로 주입하고 output log에 값을 출력하지 않아야 한다.
  • Browser automation이 사용할 Chrome 계열 executable과 container runtime이 준비되어야 한다.
  • 실행 전 현재 volume이 필요하다면 별도 project로 복제하거나 backup·snapshot을 만들어야 한다.

순서와 기대 결과

  1. 한 번에 한 pattern tip만 대상으로 선택한다. 여러 pattern stack을 같은 port에 동시에 올리지 않는다.
  2. Static realm validation과 unit test를 먼저 실행한다. 여기서 client type, redirect URI, audience mapper 또는 controller contract가 실패하면 browser E2E로 진행하지 않는다.
  3. Disposable volume이라는 것을 다시 확인한 뒤 해당 pattern stack을 build한다. Health check가 안정되지 않으면 login test를 시작하지 않는다.
  4. Browser E2E를 실행하고 위 표의 endpoint별 status, cookie flag, network 요청과 payload key를 확인한다.
  5. Pattern-specific negative input까지 모두 관측한 뒤에만 boundary가 유지된다고 판단한다.
  6. 검증이 끝나면 test용 stack을 내리고, backup이 필요했던 환경이라면 원래 project와 volume을 복구한 뒤 health와 login을 다시 확인한다.

중단 조건

  • 대상 volume의 소유와 용도를 확정할 수 없음
  • Redirect URI나 host가 test fixture와 다른 실제 environment를 가리킴
  • Secret이 command line, browser output 또는 version-controlled file에 노출됨
  • Health check, expected 401·403 또는 header overwrite 중 하나라도 불일치함

이 경우 나머지 단계를 계속 실행해 “전체 PASS”를 만들면 안 된다. 실패한 hop의 actual input과 output을 먼저 보존하고, 설정·network·application 중 어느 경계가 깨졌는지 분리해 진단해야 한다.

얻은 것, 잃은 것, 적용하지 않을 때

네 패턴은 사다리가 아니라 서로 다른 운영 계약이다

AP1에서 AP4로 갈수록 browser의 OAuth token 노출이 줄어드는 경향은 있다. 그러나 그것만으로 AP4가 AP1보다 항상 우월하다고 결론 내릴 수는 없다. State와 신뢰가 다른 계층으로 이동하기 때문이다.

패턴 얻는 것 잃거나 추가하는 것 잘 맞는 조건 피해야 할 조건
AP1 protocol 가시성, stateless Resource Server, direct API browser token lifecycle, XSS 시 token·권한 악용, reload state 포기 public SPA가 API를 직접 불러야 하고 token-in-browser를 수용 browser token 자체가 정책상 금지
AP2 client secret·refresh token server custody, 기존 Bearer API 유지 access token 노출과 server state를 동시에 운영 direct browser-to-API가 실제 요구이며 refresh credential만 분리 one-time handoff나 tokenless browser가 요구
AP3 OAuth token 비노출, application-owned fan-out과 session CSRF, shared session/token store, BFF latency와 장애 지점 backend가 API composition과 사용자 session을 소유 stateless direct API와 독립 client가 핵심
AP4 OAuth 비인지 upstream 앞의 공통 login gate proxy session, network·header trust, claim projection 계약 기존 upstream 변경이 어렵고 edge policy를 강제 가능 backend direct path나 header overwrite를 닫을 수 없음

AP1을 적용하거나 떠날 기준

AP1은 browser OAuth protocol을 직접 다뤄야 하는 SPA에서 가장 투명하다. 여러 독립 client가 같은 Resource Server를 호출하고 JWT가 self-contained API credential이어야 한다면 server session을 추가하지 않는 장점도 있다.

그러나 조직 정책이 JavaScript에 refresh token 또는 access token을 허용하지 않는다면 memory-only는 해결책이 아니다. AP2는 refresh token만 server로 옮길 수 있고 AP3는 access token까지 없앨 수 있다. Reload survival이 중요해 token을 Local Storage로 옮기려 한다면, 편의와 persistent exposure를 먼저 다시 비교해야 한다.

AP1을 유지할 때 최소 조건은 exact redirect와 origin 제한, PKCE S256, implicit·direct grant 비활성화, 짧은 access TTL, refresh rotation, issuer·audience·time·signature validation, CSP와 dependency integrity다. Admin role을 사용한다면 authentication success와 role authorization을 별도 test로 유지해야 한다.

AP2를 적용하거나 건너뛸 기준

AP2는 “Refresh token은 server에 두되 browser가 여러 Resource Server를 직접 호출한다”는 구체적 요구가 있을 때 의미가 있다. Existing Bearer API, CORS와 client-side request orchestration을 유지하면서 장기 credential만 분리할 수 있다.

반대로 단순히 “AP1보다 안전해 보인다”는 이유로 선택하면 비용 대비 경계가 모호해질 수 있다. Mediator state를 확장·복구해야 하고 access token은 여전히 XSS에 노출된다. Browser token을 금지하려는 요구라면 AP3가 더 직접적이다. Server state를 운영할 이유가 없다면 AP1이 더 단순하다.

현재 구현을 production으로 가져가려면 durable authorized-client repository, HttpSession sharing 또는 명시적 affinity, token-at-rest encryption, logout에서 두 state의 동시 삭제, refresh failure와 reauthentication, handoff rate limit이 필요하다. 정말 one-time 전달이 요구되면 raw access token endpoint를 재사용하면 안 된다. 짧은 one-time code를 발급하고 audience가 제한된 exchange endpoint에서 원자적으로 consume하는 별도 protocol이 필요하다.

AP3를 적용하거나 분해할 기준

AP3는 browser가 OAuth token을 받지 않아야 하고 backend가 UI에 맞춘 API를 조합해야 할 때 일관된 구조다. Downstream API가 여러 개여도 browser는 BFF contract 하나만 알 수 있고, token refresh와 provider-specific 세부를 server에 가둘 수 있다.

그 대가로 BFF는 단순 proxy가 아니라 stateful security component가 된다. Session replication, authorized-client storage, encryption key rotation, CSRF, rate limiting, per-route authorization, timeout과 failure mapping, logout을 운영해야 한다. BFF가 병목이나 single point of failure가 되지 않는 용량·관측 설계도 필요하다.

현재 preference example처럼 process-global object에 사용자 state를 두면 BFF를 선택한 이유와 무관하게 데이터 격리가 깨진다. User별 state는 authenticated stable subject를 key로 삼는 repository와 authorization boundary로 옮겨야 한다. AtomicReference는 CSRF demo의 observable state일 뿐 production model이 아니다.

AP4를 적용하거나 경계를 되돌릴 기준

AP4는 upstream이 OAuth library를 넣기 어렵거나 여러 legacy service 앞에 동일한 authentication gate를 두려는 경우에 강하다. Upstream이 provider token 형식을 몰라도 되고, login route와 session policy를 edge에서 통일할 수 있다.

하지만 proxy가 붙였다는 이유만으로 header를 믿는 순간 edge가 전체 인증의 root of trust가 된다. 외부에서 backend로 가는 우회 path, client-supplied header passthrough, broad trusted proxy range, shared secret 노출 중 하나라도 있으면 identity spoofing으로 이어질 수 있다. Network policy, header overwrite와 workload identity를 독립된 방어선으로 유지해야 한다.

현재 fixture는 /api/edge/를 모두 /edge/me로 바꾸므로 generic reverse proxy의 path, method, body, streaming, websocket, large header 동작을 입증하지 않는다. 실제 upstream을 붙일 때는 URI rewrite, request body, timeout, retry, response header, logout, state-changing request protection을 별도로 설계해야 한다.

Traefik ForwardAuth로 교체할 수도 있지만 현재 Nginx와 같은 속성을 내려면 최소 네 가지가 필요하다. trustForwardHeader=false, allowlisted auth response header만 복사, 별도 login redirect UX, upstream internal-token 또는 더 강한 workload identity 주입이다. 현재 대안 설정은 마지막 항목이 없으므로 drop-in equivalence가 입증되지 않았다.

변경 경로도 credential contract의 변화로 본다

AP1에서 AP2로 이동하면 Resource Server의 Bearer 계약은 유지할 수 있다. 대신 OAuth callback이 SPA에서 mediator로 이동하고 browser는 access endpoint와 session cookie를 새로 다룬다. CORS origin도 AP2 UI로 바뀐다.

AP2에서 AP3로 이동하면 더 큰 변화가 생긴다. Browser의 /token/access와 direct /api/me 호출을 제거하고 모든 UI API를 /bff/** contract로 바꿔야 한다. Server는 downstream error mapping과 CSRF를 소유한다.

AP3에서 AP4로 이동하는 것은 단순한 “한 단계 업그레이드”가 아니다. Application-owned session과 API orchestration을 edge-owned session과 identity projection으로 바꾸는 ownership 전환이다. 세밀한 per-user authorization이 BFF에 있었다면 이를 upstream 또는 별도 policy service에 다시 배치해야 한다.

반대 방향도 가능하다. AP4 upstream이 claim과 application workflow를 점점 더 많이 요구한다면 BFF로 책임을 되돌리는 것이 header contract를 무한히 확장하는 것보다 명확할 수 있다. 패턴 이동의 기준은 번호가 아니라 새 owner가 감당할 state와 verification contract다.

AP1에서 AP2, AP2에서 AP3, AP3에서 AP4, AP4에서 AP3로 이동할 때 호출 계약, 소유권, 브라우저 계약, 운영 책임과 전환 성격을 같은 다섯 축으로 비교한 네 항목.

Diagram description

네 항목을 호출 계약, 소유권, 브라우저 계약, 운영 책임, 전환 성격의 다섯 축으로 비교한다. AP1에서 AP2는 Resource Server의 Bearer 계약을 유지하면서 OAuth callback을 mediator로 옮긴다. AP2에서 AP3는 browser의 access endpoint와 direct API 호출을 없애고 UI API를 BFF 계약으로 바꾼다. AP3에서 AP4는 application-owned session과 orchestration을 edge-owned session과 identity projection으로 전환한다. AP4에서 AP3로 되돌아가는 선택도 별도 항목으로 두어 번호 순서나 성숙도 상승을 암시하지 않는다.

Editable source · Grounded VizSpec

결국 지키려던 것은 무엇이었나

네 패턴의 핵심은 token을 무조건 browser에서 더 멀리 보내는 데 있지 않다. Code를 교환하는 주체, 장기 credential을 보관하는 주체, API 요청을 만드는 주체, identity를 최종 검증하는 주체를 일치시키고 그 사이의 변환을 관측 가능하게 만드는 데 있다.

선택 전에 다음 질문에 구체적인 데이터 이름으로 답해야 한다.

  • Browser JavaScript가 access token response를 받아도 되는가?
  • Refresh token과 login session은 어느 저장소에서 restart와 replica 이동을 견딜 것인가?
  • API의 실제 caller는 browser, BFF, edge 중 누구여야 하는가?
  • 보호 자원은 signed JWT를 검증하는가, 아니면 trusted edge header를 검증하는가?
  • Cookie가 credential이면 어느 state-changing endpoint에서 CSRF를 어떻게 검증하는가?
  • Role과 account identity는 어느 claim에서 어떤 application 권한으로 바뀌는가?
  • 401, 403, refresh failure와 logout을 어느 계층이 최종 HTTP output으로 번역하는가?

이 답을 endpoint, handler, intermediate object, next-hop input과 response까지 적을 수 있어야 경계가 실제 코드가 된다. AP1, AP2, AP3, AP4라는 이름은 그 뒤에 붙는 요약일 뿐이다.