Compare commits

..
27 changed files with 1165 additions and 509 deletions
-2
View File
@@ -10,8 +10,6 @@ POSTGRES_PASSWORD=change-me-postgres-password
TOKEN_MEDIATING_CLIENT_SECRET=change-me-token-mediating-client-secret
BFF_CLIENT_SECRET=change-me-bff-client-secret
EDGE_PROXY_CLIENT_SECRET=change-me-edge-proxy-client-secret
OAUTH2_PROXY_COOKIE_SECRET=generate-a-base64-encoded-32-byte-secret
INTERNAL_AUTH_TOKEN=generate-a-long-random-edge-to-backend-token
ADMIN_USER_PASSWORD=change-me-admin-user-password
REGULAR_USER_PASSWORD=change-me-regular-user-password
+20 -13
View File
@@ -97,21 +97,28 @@ Keycloak을 잠시 중지하고 export한 뒤 자동으로 다시 올립니다.
runtime export에는 실제 client secret과 credential hash가 포함될 수 있어
gitignored `build/keycloak-export/`에 권한 `0600`으로만 저장됩니다.
## AP4: oauth2-proxy Edge Forward Auth
## AP1: SPA Direct + Resource Server
`develop-keycloak-pattern4`는 oauth2-proxy와 Nginx `auth_request`
인증을 edge에서 강제하는 패턴입니다.
`develop-keycloak-pattern1`은 vanilla JavaScript SPA가 `spa-public` client로
Authorization Code + PKCE S256 로그인을 수행하는 패턴입니다. access/refresh
token은 명시적인 in-memory store에만 보관되므로 새로고침하면 사라집니다.
```bash
./scripts/verify-pattern4.sh
./scripts/verify-pattern1.sh
```
첫 feature에서는 oauth2-proxy를 `http://localhost:4180`에 직접 노출해
OIDC redirect/PKCE/callback과 forwarded-user를 분리 확인합니다. 두 번째
feature부터 `http://localhost:8088` Nginx가 단일 진입점이며, 내부
`auth_request`는 브라우저 요청을 login 302로, API 요청을 JSON 401로
구분합니다. 최종 feature에서는 backend와 oauth2-proxy의 호스트 노출을
제거하고 Nginx 헤더 덮어쓰기와 내부 토큰 검증으로 spoofing을 막습니다.
자세한 내용은
[`docs/ap4-edge-forward-auth.md`](docs/ap4-edge-forward-auth.md)를
참고하세요.
브라우저에서 `http://localhost:8088`을 열어 로그인한 뒤 보호 API를 호출할 수
있습니다. SPA는 `http://localhost:8081/api/me`를 직접 호출하며 Spring
Resource Server가 Bearer JWT를 검증합니다.
Keycloak의 dedicated audience mapper는 `spa-public` access token에
`keycloak-pattern-api`를 추가합니다. Spring은 signature, `iss`, `exp`
아니라 이 `aud`도 검사합니다. `verify-pattern1.sh`는 같은 정상 토큰을
`deliberately-wrong-audience`를 기대하는 진단 인스턴스에도 제출해 `401`
확인합니다.
Keycloak은 `KC_HOSTNAME=http://localhost:8080`을 기준으로 token의 `iss`
발급합니다. 정상 Resource Server는 이 외부 issuer 문자열을 검증하되 JWKS는
Docker 내부의 `http://keycloak:8080`에서 가져옵니다. 진단 인스턴스는 일부러
`http://wrong-issuer.invalid`를 기대하도록 구성되어, 서명과 audience가
정상이더라도 issuer mismatch로 `401`을 반환합니다.
@@ -0,0 +1,29 @@
package com.example.keycloakpattern;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
final class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private static final OAuth2Error MISSING_AUDIENCE = new OAuth2Error(
"invalid_token",
"The required resource audience is missing",
null
);
private final String expectedAudience;
AudienceValidator(String expectedAudience) {
this.expectedAudience = expectedAudience;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
if (jwt.getAudience().contains(expectedAudience)) {
return OAuth2TokenValidatorResult.success();
}
return OAuth2TokenValidatorResult.failure(MISSING_AUDIENCE);
}
}
@@ -1,59 +0,0 @@
package com.example.keycloakpattern;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.LinkedHashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EdgeIdentityController {
private final byte[] internalAuthToken;
EdgeIdentityController(@Value("${edge.internal-auth-token}") String internalAuthToken) {
if (!hasText(internalAuthToken)) {
throw new IllegalStateException("edge.internal-auth-token must be configured");
}
this.internalAuthToken = internalAuthToken.getBytes(StandardCharsets.UTF_8);
}
@GetMapping("/edge/me")
ResponseEntity<Map<String, Object>> currentUser(HttpServletRequest request) {
String authRequestUser = request.getHeader("X-Auth-Request-User");
if (!hasText(authRequestUser) || !hasValidInternalToken(request)) {
return ResponseEntity.status(401).body(Map.of(
"error",
"trusted edge authentication is required"
));
}
Map<String, Object> response = new LinkedHashMap<>();
response.put("pattern", "AP4-edge-forward-auth");
response.put("user", authRequestUser);
response.put("email", request.getHeader("X-Auth-Request-Email"));
response.put("identityHeader", "X-Auth-Request-User");
return ResponseEntity.ok(response);
}
private boolean hasValidInternalToken(HttpServletRequest request) {
String suppliedToken = request.getHeader("X-Internal-Auth-Token");
if (!hasText(suppliedToken)) {
return false;
}
return MessageDigest.isEqual(
internalAuthToken,
suppliedToken.getBytes(StandardCharsets.UTF_8)
);
}
private static boolean hasText(String value) {
return value != null && !value.isBlank();
}
}
@@ -0,0 +1,31 @@
package com.example.keycloakpattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
@Configuration
public class JwtDecoderConfig {
@Bean
JwtDecoder jwtDecoder(
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuer,
@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}") String jwkSetUri,
@Value("${security.expected-audience}") String expectedAudience
) {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
OAuth2TokenValidator<Jwt> issuerAndTimestamp =
JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator<Jwt> audience = new AudienceValidator(expectedAudience);
decoder.setJwtValidator(
new DelegatingOAuth2TokenValidator<>(issuerAndTimestamp, audience)
);
return decoder;
}
}
@@ -1,11 +1,16 @@
package com.example.keycloakpattern;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
public class SecurityConfig {
@@ -13,20 +18,31 @@ public class SecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
return http
.cors(Customizer.withDefaults())
.csrf(csrf -> csrf.disable())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(
"/actuator/health",
"/actuator/health/**",
"/api/public",
"/edge/**"
)
.requestMatchers("/actuator/health", "/actuator/health/**", "/api/public")
.permitAll()
.anyRequest()
.authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of(
"http://localhost:8088",
"http://127.0.0.1:8088"
));
configuration.setAllowedMethods(List.of("GET", "OPTIONS"));
configuration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", configuration);
return source;
}
}
+3 -3
View File
@@ -1,9 +1,6 @@
server:
port: ${SERVER_PORT:8081}
edge:
internal-auth-token: ${EDGE_INTERNAL_AUTH_TOKEN:}
spring:
application:
name: keycloak-pattern-api
@@ -14,6 +11,9 @@ spring:
issuer-uri: ${SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUER_URI:http://localhost:8080/realms/keycloak-patterns}
jwk-set-uri: ${SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI:http://localhost:8080/realms/keycloak-patterns/protocol/openid-connect/certs}
security:
expected-audience: ${SECURITY_EXPECTED_AUDIENCE:keycloak-pattern-api}
management:
endpoint:
health:
@@ -11,7 +11,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest(properties = "edge.internal-auth-token=test-internal-edge-token")
@SpringBootTest
@AutoConfigureMockMvc
class ApiSecurityTest {
@@ -40,36 +40,4 @@ class ApiSecurityTest {
.andExpect(jsonPath("$.subject").value("test-subject"))
.andExpect(jsonPath("$.username").value("regular-user"));
}
@Test
void edgeEndpointRejectsMissingTrustedHeaders() throws Exception {
mockMvc.perform(get("/edge/me"))
.andExpect(status().isUnauthorized());
}
@Test
void edgeEndpointRejectsForgedIdentityWithoutInternalToken() throws Exception {
mockMvc.perform(get("/edge/me")
.header("X-Auth-Request-User", "spoofed-admin"))
.andExpect(status().isUnauthorized());
}
@Test
void edgeEndpointRejectsWrongInternalToken() throws Exception {
mockMvc.perform(get("/edge/me")
.header("X-Auth-Request-User", "spoofed-admin")
.header("X-Internal-Auth-Token", "wrong-token"))
.andExpect(status().isUnauthorized());
}
@Test
void edgeEndpointAcceptsIdentityFromTrustedEdge() throws Exception {
mockMvc.perform(get("/edge/me")
.header("X-Auth-Request-User", "regular-user")
.header("X-Auth-Request-Email", "regular-user@example.test")
.header("X-Internal-Auth-Token", "test-internal-edge-token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user").value("regular-user"))
.andExpect(jsonPath("$.identityHeader").value("X-Auth-Request-User"));
}
}
@@ -0,0 +1,49 @@
package com.example.keycloakpattern;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
class AudienceValidatorTest {
private final AudienceValidator validator =
new AudienceValidator("keycloak-pattern-api");
@Test
void acceptsRequiredAudience() {
OAuth2TokenValidatorResult result = validator.validate(jwtWithAudience(
List.of("account", "keycloak-pattern-api")
));
assertThat(result.hasErrors()).isFalse();
}
@Test
void rejectsForeignAudience() {
OAuth2TokenValidatorResult result = validator.validate(jwtWithAudience(
List.of("another-resource")
));
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors())
.extracting(error -> error.getErrorCode())
.containsExactly("invalid_token");
}
private Jwt jwtWithAudience(List<String> audience) {
Instant now = Instant.now();
return new Jwt(
"test-token",
now,
now.plusSeconds(300),
Map.of("alg", "none"),
Map.of("sub", "test-subject", "aud", audience)
);
}
}
+44 -51
View File
@@ -69,9 +69,8 @@ services:
SERVER_PORT: "8081"
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUER_URI: http://localhost:8080/realms/keycloak-patterns
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI: http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/certs
EDGE_INTERNAL_AUTH_TOKEN: ${INTERNAL_AUTH_TOKEN:?set INTERNAL_AUTH_TOKEN in .env}
expose:
- "8081"
ports:
- "127.0.0.1:8081:8081"
depends_on:
keycloak:
condition: service_healthy
@@ -87,67 +86,65 @@ services:
- keycloak-net
restart: unless-stopped
oauth2-proxy:
image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2
command:
- --http-address=0.0.0.0:4180
- --provider=keycloak-oidc
- --oidc-issuer-url=http://localhost:8080/realms/keycloak-patterns
- --skip-oidc-discovery=true
- --login-url=http://localhost:8080/realms/keycloak-patterns/protocol/openid-connect/auth
- --redeem-url=http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/token
- --oidc-jwks-url=http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/certs
- --profile-url=http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/userinfo
- --validate-url=http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/userinfo
- --redirect-url=http://localhost:8088/oauth2/callback
- --upstream=http://app:8081
- --email-domain=*
- --scope=openid profile email
- --code-challenge-method=S256
- --reverse-proxy=true
- --trusted-proxy-ip=172.30.40.10/32
- --cookie-name=AP4_SESSION
- --cookie-secure=false
- --cookie-samesite=lax
- --cookie-expire=1h
- --skip-provider-button=true
- --set-xauthrequest=true
- --pass-user-headers=true
- --whitelist-domain=localhost:8088
- --whitelist-domain=localhost:8080
app-wrong-audience:
profiles:
- diagnostics
build:
context: ./backend
environment:
OAUTH2_PROXY_CLIENT_ID: edge-proxy
OAUTH2_PROXY_CLIENT_SECRET: ${EDGE_PROXY_CLIENT_SECRET:?set EDGE_PROXY_CLIENT_SECRET in .env}
OAUTH2_PROXY_COOKIE_SECRET: ${OAUTH2_PROXY_COOKIE_SECRET:?set OAUTH2_PROXY_COOKIE_SECRET in .env}
expose:
- "4180"
SERVER_PORT: "8081"
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUER_URI: http://localhost:8080/realms/keycloak-patterns
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI: http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/certs
SECURITY_EXPECTED_AUDIENCE: deliberately-wrong-audience
ports:
- "127.0.0.1:18081:8081"
depends_on:
keycloak:
condition: service_healthy
app:
healthcheck:
test:
- CMD-SHELL
- wget -q -O - http://127.0.0.1:8081/actuator/health | grep -q '"status":"UP"'
interval: 10s
timeout: 5s
retries: 12
start_period: 20s
networks:
- keycloak-net
app-wrong-issuer:
profiles:
- diagnostics
build:
context: ./backend
environment:
SERVER_PORT: "8081"
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUER_URI: http://wrong-issuer.invalid/realms/keycloak-patterns
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI: http://keycloak:8080/realms/keycloak-patterns/protocol/openid-connect/certs
SECURITY_EXPECTED_AUDIENCE: keycloak-pattern-api
ports:
- "127.0.0.1:18082:8081"
depends_on:
keycloak:
condition: service_healthy
healthcheck:
test:
- CMD
- /bin/oauth2-proxy
- --version
- CMD-SHELL
- wget -q -O - http://127.0.0.1:8081/actuator/health | grep -q '"status":"UP"'
interval: 10s
timeout: 5s
retries: 3
start_period: 5s
retries: 12
start_period: 20s
networks:
- keycloak-net
restart: unless-stopped
nginx:
build:
context: ./frontend
environment:
INTERNAL_AUTH_TOKEN: ${INTERNAL_AUTH_TOKEN:?set INTERNAL_AUTH_TOKEN in .env}
ports:
- "127.0.0.1:${NGINX_PORT:-8088}:80"
depends_on:
oauth2-proxy:
app:
condition: service_healthy
healthcheck:
test:
@@ -157,8 +154,7 @@ services:
timeout: 5s
retries: 12
networks:
keycloak-net:
ipv4_address: 172.30.40.10
- keycloak-net
restart: unless-stopped
volumes:
@@ -168,6 +164,3 @@ volumes:
networks:
keycloak-net:
driver: bridge
ipam:
config:
- subnet: 172.30.40.0/24
-70
View File
@@ -1,70 +0,0 @@
# AP4 · oauth2-proxy Edge Forward Auth
## 첫 단계: oauth2-proxy 자체 OIDC 흐름
`feature/keycloak-oauth2-proxy-oidc-flow`에서는 oauth2-proxy를
`http://localhost:4180`에 직접 노출해 구성 요소를 분리해서 확인합니다.
1. `/edge/me` 미인증 요청이 Keycloak로 redirect됩니다.
2. oauth2-proxy는 confidential `edge-proxy` client와 PKCE S256을 사용합니다.
3. callback에서 code/token 교환과 ID/access token 검증은 서버끼리
수행합니다.
4. 브라우저에는 HttpOnly `AP4_SESSION` cookie만 남습니다.
5. oauth2-proxy가 backend 요청에 `X-Forwarded-User`를 붙여 200을 받습니다.
Keycloak이 발급하는 issuer는 브라우저 기준
`http://localhost:8080/realms/keycloak-patterns`입니다. 컨테이너 내부의
`localhost`는 oauth2-proxy 자신이므로 discovery endpoint에 도달할 수
없습니다. 그래서 이 로컬 Compose 구성은 issuer 검증값은 외부 URL로
유지하되, login URL은 브라우저용 외부 주소, token/JWKS/userinfo는
`http://keycloak:8080` 내부 주소로 각각 명시합니다.
HTTP 로컬 시연이라 `cookie-secure=false`를 사용합니다. 운영 HTTPS에서는
반드시 secure cookie로 되돌려야 합니다.
## 다음 단계의 보안 전제
이 첫 feature의 backend는 전달된 사용자 헤더를 신뢰하며 8081도
loopback에 publish되어 있습니다. 따라서 로컬에서 직접
`X-Forwarded-User: spoofed-admin`을 보내면 우회가 재현됩니다. 이후
Nginx `auth_request` 통합을 거쳐 최종 feature에서 backend no-publish와
내부 shared-secret 검증을 함께 적용합니다.
## 두 번째 단계: Nginx `auth_request`
`feature/keycloak-nginx-auth-request-integration`부터 외부 진입점은
`http://localhost:8088` Nginx 하나입니다. oauth2-proxy의 4180 포트는
Compose 네트워크에만 expose됩니다.
- Nginx의 정확 일치 `location = /oauth2/auth``internal`이라 외부에서
직접 호출할 수 없습니다.
- 인증 서브리퀘스트에는 본문을 보내지 않고 `Content-Length`
비웁니다.
- 일반 브라우저 요청의 401은 `/oauth2/start` 302로 변환합니다.
- API 요청 `/api/edge`는 redirect하지 않고 JSON 401을 반환합니다.
- 인증 성공 시 oauth2-proxy의 `X-Auth-Request-User`와 email만 backend로
전달합니다.
Nginx 컨테이너 IP를 전용 Compose subnet에서 고정하고 oauth2-proxy의
trusted proxy를 그 단일 IP로 제한합니다. 다만 이 단계에서는 backend
8081이 로컬 호스트에 열려 있어 신뢰 헤더를 직접 위조할 수 있습니다.
그 재현 조건은 마지막 feature에서 제거합니다.
## 마지막 단계: 신뢰 경계와 헤더 스푸핑 방어
`feature/keycloak-header-spoofing-defense`에서는 신뢰 경계를 실제
네트워크와 application 양쪽에서 강제합니다.
1. backend 8081과 oauth2-proxy 4180은 host에 publish하지 않습니다.
브라우저가 접근 가능한 application 포트는 Nginx 8088뿐입니다.
2. Nginx는 client가 보낸 `X-Auth-Request-User`, email, 내부 토큰을
그대로 전달하지 않고 oauth2-proxy 결과와 server-side 토큰으로
항상 덮어씁니다.
3. backend는 `X-Auth-Request-User``X-Internal-Auth-Token`이 모두
유효할 때만 edge identity를 받아들이며 token은 constant-time으로
비교합니다.
shared token은 방어 심층화 수단입니다. 운영에서는 Secret Manager나
orchestrator secret으로 주입하고 주기적으로 교체해야 합니다. 서비스
간 mTLS 또는 service mesh identity를 사용할 수 있다면 단순 shared
token보다 강한 workload identity로 대체하는 편이 좋습니다.
+1 -1
View File
@@ -4,7 +4,7 @@
"version": "1.0.0",
"type": "module",
"scripts": {
"test:pattern4": "node pattern4.mjs"
"test:pattern1": "node pattern1.mjs"
},
"devDependencies": {
"playwright-core": "1.62.0"
+101
View File
@@ -0,0 +1,101 @@
import assert from "node:assert/strict";
import { chromium } from "playwright-core";
const username = process.env.E2E_USERNAME ?? "regular-user";
const password = process.env.E2E_PASSWORD;
assert.ok(password, "E2E_PASSWORD must be set");
const browser = await chromium.launch({
executablePath: process.env.CHROME_BIN ?? "/usr/bin/google-chrome",
headless: true,
args: ["--no-sandbox"],
});
try {
const context = await browser.newContext();
const page = await context.newPage();
let authorizationUrl;
page.on("request", (request) => {
if (request.url().includes("/protocol/openid-connect/auth")) {
authorizationUrl = new URL(request.url());
}
});
await page.goto("http://localhost:8088");
await page.locator("#login").click();
await page.waitForURL(/localhost:8080/u);
await page.locator("#username").fill(username);
await page.locator("#password").fill(password);
await page.locator("#kc-login").click();
await page.waitForURL("http://localhost:8088/");
await page.locator('[data-authenticated="true"]').waitFor();
assert.equal(authorizationUrl?.searchParams.get("response_type"), "code");
assert.equal(authorizationUrl?.searchParams.get("code_challenge_method"), "S256");
assert.ok(authorizationUrl?.searchParams.get("code_challenge"));
const accessToken = await page.evaluate(() => window.__pattern1.getAccessToken());
assert.ok(accessToken, "access token must exist in browser memory");
const payload = JSON.parse(
Buffer.from(accessToken.split(".")[1], "base64url").toString("utf8"),
);
const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
assert.ok(
audiences.includes("keycloak-pattern-api"),
"access token must target keycloak-pattern-api",
);
const storageSnapshot = await page.evaluate(() => ({
localStorage: Object.values(localStorage),
sessionStorage: Object.values(sessionStorage),
}));
assert.equal(
JSON.stringify(storageSnapshot).includes(accessToken),
false,
"access token must not be persisted in Web Storage",
);
await page.locator("#call-api").click();
await page.waitForFunction(() => {
const text = document.querySelector("#result")?.textContent ?? "";
return text.includes('"httpStatus": 200');
});
if (process.env.WRONG_AUDIENCE_URL) {
const response = await fetch(process.env.WRONG_AUDIENCE_URL, {
headers: { Authorization: `Bearer ${accessToken}` },
});
assert.equal(
response.status,
401,
"the same signed token must fail when the Resource Server expects another audience",
);
}
if (process.env.WRONG_ISSUER_URL) {
const response = await fetch(process.env.WRONG_ISSUER_URL, {
headers: { Authorization: `Bearer ${accessToken}` },
});
assert.equal(
response.status,
401,
"the same signed token must fail when the Resource Server expects another issuer",
);
}
await page.reload();
await page.locator('[data-authenticated="false"]').waitFor();
assert.equal(
await page.evaluate(() => window.__pattern1.getAccessToken()),
null,
"reload must clear the memory-only token",
);
console.log(
"pattern1 browser verified: code+PKCE S256, audience/issuer negatives 401, Web Storage token 0, reload clears token",
);
} finally {
await browser.close();
}
-138
View File
@@ -1,138 +0,0 @@
import assert from "node:assert/strict";
import { chromium } from "playwright-core";
const password = process.env.E2E_PASSWORD;
assert.ok(password, "E2E_PASSWORD must be set");
const edgeBaseUrl = "http://localhost:8088";
const edgeEntryUrl = `${edgeBaseUrl}/`;
async function completeKeycloakLogin(page) {
for (let attempt = 1; attempt <= 2; attempt += 1) {
await page.locator("#username").fill(
process.env.E2E_USERNAME ?? "regular-user",
);
await page.locator("#password").fill(password);
await page.locator("#kc-login").click();
await page.waitForLoadState("domcontentloaded");
if (page.url() === edgeEntryUrl) {
return;
}
if (attempt === 1) {
await page.goto(`${edgeBaseUrl}/oauth2/start?rd=${encodeURIComponent(edgeEntryUrl)}`);
await page.waitForURL(/localhost:8080/u);
}
}
throw new Error(`Keycloak login did not return to AP4: ${page.url()}`);
}
const browser = await chromium.launch({
executablePath: process.env.CHROME_BIN ?? "/usr/bin/google-chrome",
headless: true,
args: ["--no-sandbox"],
});
try {
const context = await browser.newContext();
const page = await context.newPage();
const browserRequests = [];
page.on("request", (request) =>
browserRequests.push({ method: request.method(), url: request.url() }),
);
const edgeResponsePromise = page.waitForResponse(
(response) =>
response.url() === edgeEntryUrl &&
response.status() === 302,
);
const authorizationRequestPromise = page.waitForRequest((request) =>
request.url().includes(
"/protocol/openid-connect/auth?approval_prompt=",
),
);
await page.goto(edgeEntryUrl);
const unauthenticatedEdgeResponse = await edgeResponsePromise;
assert.equal(unauthenticatedEdgeResponse.status(), 302);
const authorizationRequest = await authorizationRequestPromise;
const authorizationUrl = new URL(authorizationRequest.url());
assert.equal(authorizationUrl.searchParams.get("client_id"), "edge-proxy");
assert.equal(authorizationUrl.searchParams.get("code_challenge_method"), "S256");
assert.ok(authorizationUrl.searchParams.get("code_challenge"));
await page.waitForURL(/localhost:8080/u);
await completeKeycloakLogin(page);
const edgeIdentity = JSON.parse(await page.locator("body").innerText());
assert.equal(edgeIdentity.pattern, "AP4-edge-forward-auth");
assert.ok(edgeIdentity.user);
assert.equal(edgeIdentity.identityHeader, "X-Auth-Request-User");
const callbackRequest = browserRequests.find(({ url }) =>
url.startsWith(`${edgeBaseUrl}/oauth2/callback?`),
);
assert.ok(callbackRequest);
assert.equal(callbackRequest.method, "GET");
assert.equal(
browserRequests.some(({ url }) =>
url.includes("/protocol/openid-connect/token"),
),
false,
"the confidential token exchange must be server-to-server",
);
const cookies = await context.cookies(edgeEntryUrl);
const sessionCookie = cookies.find((cookie) => cookie.name === "AP4_SESSION");
assert.ok(sessionCookie);
assert.equal(sessionCookie.httpOnly, true);
assert.equal(sessionCookie.sameSite, "Lax");
assert.equal(sessionCookie.secure, false);
const storage = await page.evaluate(() => ({
localStorage: Object.values(localStorage),
sessionStorage: Object.values(sessionStorage),
readableCookies: document.cookie,
}));
assert.deepEqual(storage.localStorage, []);
assert.deepEqual(storage.sessionStorage, []);
assert.equal(storage.readableCookies.includes("AP4_SESSION"), false);
const spoofAttempt = await page.evaluate(async () => {
const response = await fetch("/", {
headers: {
"X-Auth-Request-User": "spoofed-admin",
"X-Auth-Request-Email": "spoofed-admin@example.test",
"X-Internal-Auth-Token": "attacker-controlled-token",
},
});
return { status: response.status, body: await response.json() };
});
assert.equal(spoofAttempt.status, 200);
assert.equal(spoofAttempt.body.user, edgeIdentity.user);
assert.notEqual(spoofAttempt.body.user, "spoofed-admin");
const externalAuthSubrequest = await fetch(`${edgeBaseUrl}/oauth2/auth`);
assert.equal(externalAuthSubrequest.status, 404);
const apiResponse = await fetch(`${edgeBaseUrl}/api/edge`, {
redirect: "manual",
});
assert.equal(apiResponse.status, 401);
assert.equal(apiResponse.headers.get("location"), null);
await assert.rejects(
fetch("http://localhost:4180/ping"),
"oauth2-proxy must not be published on the host",
);
await assert.rejects(
fetch("http://localhost:8081/edge/me"),
"backend must not be published on the host",
);
console.log(
"pattern4 hardened edge verified: auth_request, no backend publish, spoofed headers overwritten",
);
} finally {
await browser.close();
}
+13 -1
View File
@@ -1,4 +1,16 @@
FROM node:24-alpine AS build
WORKDIR /workspace
COPY package.json package-lock.json ./
RUN npm ci
COPY src ./src
COPY test ./test
RUN npm test && npm run build
FROM nginx:1.29-alpine
COPY default.conf.template /etc/nginx/templates/default.conf.template
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY index.html /usr/share/nginx/html/index.html
COPY --from=build /workspace/dist/app.js /usr/share/nginx/html/app.js
-75
View File
@@ -1,75 +0,0 @@
server {
listen 80;
server_name _;
large_client_header_buffers 4 16k;
location = /health {
access_log off;
default_type text/plain;
return 200 "ok\n";
}
location = /oauth2/auth {
internal;
proxy_pass http://oauth2-proxy:4180;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Uri $request_uri;
}
location /oauth2/ {
proxy_pass http://oauth2-proxy:4180;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Auth-Request-Redirect $scheme://$http_host$request_uri;
}
location = /api/edge {
auth_request /oauth2/auth;
error_page 401 = @api_unauthorized;
auth_request_set $auth_user $upstream_http_x_auth_request_user;
auth_request_set $auth_email $upstream_http_x_auth_request_email;
auth_request_set $auth_cookie $upstream_http_set_cookie;
add_header Set-Cookie $auth_cookie always;
proxy_pass http://app:8081/edge/me;
proxy_set_header X-Auth-Request-User $auth_user;
proxy_set_header X-Auth-Request-Email $auth_email;
proxy_set_header X-Internal-Auth-Token "${INTERNAL_AUTH_TOKEN}";
}
location / {
auth_request /oauth2/auth;
error_page 401 = @oauth2_signin;
auth_request_set $auth_user $upstream_http_x_auth_request_user;
auth_request_set $auth_email $upstream_http_x_auth_request_email;
auth_request_set $auth_cookie $upstream_http_set_cookie;
add_header Set-Cookie $auth_cookie always;
proxy_pass http://app:8081/edge/me;
proxy_set_header X-Auth-Request-User $auth_user;
proxy_set_header X-Auth-Request-Email $auth_email;
proxy_set_header X-Internal-Auth-Token "${INTERNAL_AUTH_TOKEN}";
}
location @oauth2_signin {
return 302 $scheme://$http_host/oauth2/start?rd=$scheme://$http_host$request_uri;
}
location @api_unauthorized {
default_type application/json;
return 401 '{"error":"authentication required"}';
}
}
+48 -13
View File
@@ -3,31 +3,66 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Keycloak Authentication Patterns</title>
<meta name="referrer" content="no-referrer">
<title>AP1 · SPA Direct + Resource Server</title>
<style>
:root {
color-scheme: light dark;
font-family: system-ui, sans-serif;
}
body {
max-width: 48rem;
margin: 8vh auto;
max-width: 56rem;
margin: 6vh auto;
padding: 0 1.5rem;
line-height: 1.6;
line-height: 1.55;
}
button {
margin: 0 0.5rem 0.5rem 0;
padding: 0.6rem 0.9rem;
cursor: pointer;
}
code, pre {
border-radius: 0.35rem;
background: color-mix(in srgb, CanvasText 9%, Canvas);
}
code {
padding: 0.15rem 0.35rem;
border-radius: 0.25rem;
background: color-mix(in srgb, CanvasText 10%, Canvas);
padding: 0.1rem 0.3rem;
}
pre {
min-height: 8rem;
padding: 1rem;
overflow: auto;
white-space: pre-wrap;
}
.notice {
border-left: 0.3rem solid #e09f3e;
padding-left: 1rem;
}
</style>
</head>
<body>
<h1>Keycloak Authentication Patterns</h1>
<p>공통 Docker Compose baseline이 실행 중입니다.</p>
<p>
공개 API는 <code>/api/public</code>, 보호 API는
<code>/api/me</code>에서 확인할 수 있습니다.
</p>
<main>
<h1>AP1 · SPA Direct + Resource Server</h1>
<p>
바닐라 JavaScript SPA가 <code>spa-public</code> client로 Authorization
Code + PKCE를 수행하고, access token을 직접 Spring Resource Server에
전달합니다.
</p>
<p class="notice">
access/refresh token은 메모리에만 존재합니다. 새로고침하면 사라지는 것이
이 패턴의 의도된 보안 경계입니다.
</p>
<section>
<button id="login" type="button">Keycloak 로그인</button>
<button id="call-api" type="button" disabled>보호 API 호출</button>
<button id="pkce-demo" type="button">수동 PKCE 생성</button>
<button id="logout" type="button" disabled>로그아웃</button>
</section>
<p id="session-state" data-authenticated="false">세션 확인 중…</p>
<pre id="result" aria-live="polite"></pre>
</main>
<script type="module" src="/app.js"></script>
</body>
</html>
+27
View File
@@ -0,0 +1,27 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location = /health {
access_log off;
default_type text/plain;
return 200 "ok\n";
}
location /api/ {
proxy_pass http://app:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
add_header Cache-Control "no-store";
try_files $uri $uri/ /index.html;
}
}
+523
View File
@@ -0,0 +1,523 @@
{
"name": "keycloak-pattern1-spa",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "keycloak-pattern1-spa",
"version": "1.0.0",
"dependencies": {
"oidc-client-ts": "3.5.0"
},
"devDependencies": {
"esbuild": "0.28.1"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/oidc-client-ts": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/oidc-client-ts/-/oidc-client-ts-3.5.0.tgz",
"integrity": "sha512-l2q8l9CTCTOlbX+AnK4p3M+4CEpKpyQhle6blQkdFhm0IsBqsxm15bYaSa11G7pWdsYr6epdsRZxJpCyCRbT8A==",
"license": "Apache-2.0",
"dependencies": {
"jwt-decode": "^4.0.0"
},
"engines": {
"node": ">=18"
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "keycloak-pattern1-spa",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "esbuild src/app.js --bundle --format=esm --outfile=dist/app.js --minify --sourcemap",
"test": "node --test test/*.test.mjs"
},
"dependencies": {
"oidc-client-ts": "3.5.0"
},
"devDependencies": {
"esbuild": "0.28.1"
}
}
+138
View File
@@ -0,0 +1,138 @@
import {
InMemoryWebStorage,
UserManager,
WebStorageStateStore,
} from "oidc-client-ts";
import { createPkcePair } from "./pkce.js";
const authority = "http://localhost:8080/realms/keycloak-patterns";
const backendBaseUrl = "http://localhost:8081";
const userManager = new UserManager({
authority,
client_id: "spa-public",
redirect_uri: "http://localhost:8088/callback.html",
post_logout_redirect_uri: "http://localhost:8088/",
response_type: "code",
scope: "openid profile email",
automaticSilentRenew: true,
monitorSession: false,
loadUserInfo: false,
userStore: new WebStorageStateStore({
store: new InMemoryWebStorage(),
}),
stateStore: new WebStorageStateStore({
store: window.sessionStorage,
}),
});
const loginButton = document.querySelector("#login");
const logoutButton = document.querySelector("#logout");
const apiButton = document.querySelector("#call-api");
const pkceButton = document.querySelector("#pkce-demo");
const sessionState = document.querySelector("#session-state");
const result = document.querySelector("#result");
let currentUser = null;
function renderJson(value) {
result.textContent = JSON.stringify(value, null, 2);
}
function tokenMetadata(user) {
return {
subject: user.profile.sub,
username: user.profile.preferred_username,
expiresAt: new Date(user.expires_at * 1000).toISOString(),
accessTokenHeldBy: "browser memory",
refreshTokenHeldBy: user.refresh_token ? "browser memory" : "not issued",
};
}
function renderSession(user) {
currentUser = user;
const authenticated = Boolean(user && !user.expired);
sessionState.dataset.authenticated = String(authenticated);
sessionState.textContent = authenticated
? `${user.profile.preferred_username} 로그인됨 · token은 메모리에만 보관`
: "로그인되지 않음 · 브라우저 저장소에 token 없음";
loginButton.disabled = authenticated;
logoutButton.disabled = !authenticated;
apiButton.disabled = !authenticated;
if (authenticated) {
renderJson(tokenMetadata(user));
}
}
async function finishSigninCallback() {
const params = new URLSearchParams(window.location.search);
const isCallback = window.location.pathname === "/callback.html"
&& (params.has("code") || params.has("error"));
if (!isCallback) {
return null;
}
const user = await userManager.signinRedirectCallback();
window.history.replaceState({}, document.title, "/");
return user;
}
async function callProtectedApi() {
if (!currentUser || currentUser.expired) {
throw new Error("로그인이 필요합니다.");
}
const response = await fetch(`${backendBaseUrl}/api/me`, {
headers: {
Authorization: `Bearer ${currentUser.access_token}`,
},
});
const body = await response.json();
renderJson({
httpStatus: response.status,
resourceServerResponse: body,
tokenBoundary: tokenMetadata(currentUser),
});
if (!response.ok) {
throw new Error(`보호 API가 ${response.status}를 반환했습니다.`);
}
}
loginButton.addEventListener("click", () => userManager.signinRedirect());
logoutButton.addEventListener("click", () => userManager.signoutRedirect());
apiButton.addEventListener("click", () => {
callProtectedApi().catch((error) => renderJson({ error: error.message }));
});
pkceButton.addEventListener("click", () => {
createPkcePair()
.then(({ verifier, challenge, method }) => renderJson({
method,
verifierLength: verifier.length,
challengeLength: challenge.length,
note: "실제 로그인에서는 oidc-client-ts가 같은 S256 단계를 수행합니다.",
}))
.catch((error) => renderJson({ error: error.message }));
});
userManager.events.addUserLoaded(renderSession);
userManager.events.addUserUnloaded(() => renderSession(null));
userManager.events.addAccessTokenExpired(() => renderSession(null));
window.__pattern1 = {
getAccessToken: () => currentUser?.access_token ?? null,
getRefreshToken: () => currentUser?.refresh_token ?? null,
getIdToken: () => currentUser?.id_token ?? null,
callProtectedApi,
};
try {
const callbackUser = await finishSigninCallback();
renderSession(callbackUser ?? await userManager.getUser());
} catch (error) {
renderSession(null);
renderJson({ error: error.message });
}
+26
View File
@@ -0,0 +1,26 @@
function base64Url(bytes) {
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary)
.replaceAll("+", "-")
.replaceAll("/", "_")
.replace(/=+$/u, "");
}
export async function createPkcePair(cryptoApi = globalThis.crypto) {
const verifierBytes = new Uint8Array(32);
cryptoApi.getRandomValues(verifierBytes);
const verifier = base64Url(verifierBytes);
const digest = await cryptoApi.subtle.digest(
"SHA-256",
new TextEncoder().encode(verifier),
);
return {
verifier,
challenge: base64Url(new Uint8Array(digest)),
method: "S256",
};
}
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import { webcrypto } from "node:crypto";
import test from "node:test";
globalThis.btoa = (value) => Buffer.from(value, "binary").toString("base64");
const { createPkcePair } = await import("../src/pkce.js");
test("manual PKCE helper creates an RFC 7636 S256 pair", async () => {
const pair = await createPkcePair(webcrypto);
assert.equal(pair.method, "S256");
assert.equal(pair.verifier.length, 43);
assert.equal(pair.challenge.length, 43);
assert.match(pair.verifier, /^[A-Za-z0-9_-]+$/u);
assert.match(pair.challenge, /^[A-Za-z0-9_-]+$/u);
assert.notEqual(pair.verifier, pair.challenge);
});
+17 -3
View File
@@ -51,7 +51,22 @@
"attributes": {
"pkce.code.challenge.method": "S256",
"post.logout.redirect.uris": "http://localhost:8088/*##http://127.0.0.1:8088/*"
}
},
"protocolMappers": [
{
"name": "keycloak-pattern-api-audience",
"protocol": "openid-connect",
"protocolMapper": "oidc-audience-mapper",
"consentRequired": false,
"config": {
"included.custom.audience": "keycloak-pattern-api",
"id.token.claim": "false",
"access.token.claim": "true",
"userinfo.token.claim": "false",
"introspection.token.claim": "true"
}
}
]
},
{
"clientId": "token-mediating-confidential",
@@ -116,11 +131,10 @@
"serviceAccountsEnabled": false,
"frontchannelLogout": true,
"redirectUris": [
"http://localhost:8088/oauth2/callback"
"http://localhost:4180/oauth2/callback"
],
"webOrigins": [],
"attributes": {
"pkce.code.challenge.method": "S256",
"post.logout.redirect.uris": "http://localhost:8088/*"
}
}
+12
View File
@@ -70,6 +70,18 @@ def validate(path: Path, runtime: bool) -> None:
spa.get("attributes", {}).get("pkce.code.challenge.method") == "S256",
"spa-public must enforce PKCE S256",
)
audience_mappers = [
mapper
for mapper in spa.get("protocolMappers", [])
if mapper.get("protocolMapper") == "oidc-audience-mapper"
]
if not runtime:
require(len(audience_mappers) == 1, "spa-public must declare one audience mapper")
require(
audience_mappers[0].get("config", {}).get("included.custom.audience")
== "keycloak-pattern-api",
"spa-public access token must target keycloak-pattern-api",
)
for client_id, placeholder in CONFIDENTIAL_CLIENTS.items():
client = clients[client_id]
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env sh
set -eu
if [ ! -f .env ]; then
echo "missing .env; copy .env.example and set local-only values" >&2
exit 1
fi
set -a
. ./.env
set +a
docker compose down --volumes --remove-orphans
docker compose up --build -d --wait
docker compose --profile diagnostics up -d --wait \
app-wrong-audience \
app-wrong-issuer
npm --prefix e2e ci
E2E_USERNAME=regular-user \
E2E_PASSWORD="$REGULAR_USER_PASSWORD" \
WRONG_AUDIENCE_URL=http://localhost:18081/api/me \
WRONG_ISSUER_URL=http://localhost:18082/api/me \
npm --prefix e2e run test:pattern1
echo "AP1 verified end to end"
-41
View File
@@ -1,41 +0,0 @@
#!/usr/bin/env sh
set -eu
if [ ! -f .env ]; then
echo "missing .env; copy .env.example and set development values" >&2
exit 1
fi
set -a
. ./.env
set +a
docker compose down --volumes --remove-orphans
docker compose up --build -d --wait
docker compose exec -T nginx nginx -V 2>&1 |
grep -q -- '--with-http_auth_request_module'
docker compose exec -T nginx nginx -T 2>&1 |
grep -q 'proxy_pass_request_body off'
app_container_id="$(docker compose ps -q app)"
published_app_port="$(docker inspect "$app_container_id" \
--format '{{with (index .NetworkSettings.Ports "8081/tcp")}}{{json .}}{{end}}')"
if [ -n "$published_app_port" ]; then
echo "backend port 8081 must not be published on the host" >&2
exit 1
fi
if docker compose exec -T nginx wget -q -O /dev/null \
--header 'X-Auth-Request-User: spoofed-admin' \
http://app:8081/edge/me 2>/dev/null; then
echo "backend accepted a forged identity without the internal token" >&2
exit 1
fi
npm --prefix e2e ci
E2E_USERNAME=regular-user \
E2E_PASSWORD="$REGULAR_USER_PASSWORD" \
npm --prefix e2e run test:pattern4
echo "AP4 hardened Nginx auth_request edge flow verified"