본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

OpenID Connect: 토큰 변환

원문 보기 위키 갱신

OpenID Connect: 토큰 변환 (Token transformation)

이 문서는 OpenID Connect 플러그인을 사용해 스코프가 제한된 외부 토큰을 필요한 스코프를 가진 내부 토큰으로 교환하는 방법을 설명해요. 클라이언트가 제한된 토큰을 발급받는 환경에서 Kong Gateway가 특별 클라이언트로서 토큰 교환을 대신 수행해 업스트림 서비스에 접근할 수 있게 해주는 흐름을 시퀀스 다이어그램과 함께 소개해요. Keycloak을 IdP로 사용하는 전체 예제 튜토리얼 링크와 함께, 사전 요구 사항과 환경 변수, decK 설정을 통한 플러그인 구성 방법까지 안내하고 있어요

출처: 문서

본문

토큰 변환 v3.14+

OpenID Connect 플러그인을 사용하면 스코프가 제한된 외부 토큰을, 필요한 스코프를 가진 내부 토큰으로 교환할 수 있어요.

이 예제에서 클라이언트들은 업스트림 서비스를 보호하는 것과 동일한 AuthZ 서버에 등록돼요. 하지만 보안상의 이유로 클라이언트들은 제한되어 있어서 스코프가 제한된 토큰만 발급받아요. Kong Gateway는 업스트림 서비스에 접근할 수 있는 토큰(적절한 스코프 포함)을 이런 다른 클라이언트들을 대신해 요청할 수 있도록 승인된 특별한 클라이언트예요. Kong은 들어온 토큰을, 업스트림 서비스에 접근하기 위한 올바른 스코프를 가진 새 토큰으로 교환해요.

OIDC 플러그인에서 토큰 교환이 동작하는 방식은 다음과 같아요:

 
sequenceDiagram
    participant C as 클라이언트
(모바일 앱 등) participant K as 게이트웨이 participant A as 인가 서버
(Keycloak 등) participant U as 업스트림
(백엔드 서비스,
httpbin 등) C->>K: subject 토큰과 함께 요청 activate K note over K: subject 토큰 검증
(iss, exp, nbf) K->>A: 토큰 교환 요청 activate A A-->>K: 교환된 액세스 토큰 deactivate A K->>K: 교환된 토큰 검증 K->>U: 교환된 토큰과 함께 요청 전달 activate U U-->>K: 응답 deactivate U K-->>C: 응답 deactivate K

Keycloak을 IdP로 사용하는 전체 예제는 토큰 교환과 함께 OpenID Connect 구성 튜토리얼을 확인하세요.

전제 조건

  • 토큰 교환을 지원하고 두 개의 클라이언트가 구성된 identity provider(IdPs)가 필요해요. Client A는 요청할 수 있는 범위가 제한되어 있는 반면, Client 2는 토큰 교환을 수행하고 특정 스코프를 요청할 수 있도록 승인돼 있어요.

환경 변수

  • ISSUER: 들어오는 요청의 토큰을 발급한 인가 서버의 issuer 인증 URL이에요. 예를 들어 Keycloak을 IdP로 사용한다면, issuer URL은 다음과 같아요: http://localhost:8080/realms/example-realm.

  • CLIENT_ID: 플러그인이 IdP(이 경우 Server A)의 인증된 엔드포인트를 호출할 때 사용하는 클라이언트 ID예요.

  • CLIENT_SECRET: IdP(이 경우 Server A)에 연결하는 데 필요한 클라이언트 시크릿이에요.

  • TOKEN_SALT: 매 동기화마다 세션 자격 증명이 다시 생성되지 않도록 하기 위해 decK(v1.59 이상)가 필요로 하는 랜덤 문자열이에요. 이 파라미터는 다른 포맷에서는 선택 사항이에요. 예를 들어 openssl rand -base64 16으로 생성할 수 있어요.

플러그인 설정

전역

decK

다음 섹션을 kong.yaml 설정 파일에 추가하세요:

_format_version: "3.0"
plugins:
  - name: openid-connect
    config:
      issuer: ${{ env "DECK_ISSUER" }}
      client_id:
      - ${{ env "DECK_CLIENT_ID" }}
      client_secret:
      - ${{ env "DECK_CLIENT_SECRET" }}
      client_auth:
      - client_secret_post
      auth_methods:
      - bearer
      token_exchange:
        subject_token_issuers:
        - issuer: ${{ env "DECK_ISSUER" }}
          conditions:
            missing_audience:
            has_audience:
            missing_scopes:
            - profile
            has_scopes:
        request:
          empty_audience: false
          scopes:
          empty_scopes: false
          audience:
      cache_tokens_salt: ${{ env "DECK_TOKEN_SALT" }}

{: data-file="kong.yaml" data-tool="deck" }

Admin API

다음 요청을 보내세요:

curl -i -X POST http://localhost:8001/plugins/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "name": "openid-connect",
      "config": {
        "issuer": "'$ISSUER'",
        "client_id": [
          "'$CLIENT_ID'"
        ],
        "client_secret": [
          "'$CLIENT_SECRET'"
        ],
        "client_auth": [
          "client_secret_post"
        ],
        "auth_methods": [
          "bearer"
        ],
        "token_exchange": {
          "subject_token_issuers": [
            {
              "issuer": "'$ISSUER'",
              "conditions": {
                "missing_audience": null,
                "has_audience": null,
                "missing_scopes": [
                  "profile"
                ],
                "has_scopes": null
              }
            }
          ],
          "request": {
            "empty_audience": false,
            "scopes": null,
            "empty_scopes": false,
            "audience": null
          }
        },
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '
Konnect API

다음 요청을 보내세요:

curl -X POST https://{region}.api.konghq.com/v2/control-planes/{controlPlaneId}/core-entities/plugins/ \
    --header "accept: application/json" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer $KONNECT_TOKEN" \
    --data '
    {
      "name": "openid-connect",
      "config": {
        "issuer": "'$ISSUER'",
        "client_id": [
          "'$CLIENT_ID'"
        ],
        "client_secret": [
          "'$CLIENT_SECRET'"
        ],
        "client_auth": [
          "client_secret_post"
        ],
        "auth_methods": [
          "bearer"
        ],
        "token_exchange": {
          "subject_token_issuers": [
            {
              "issuer": "'$ISSUER'",
              "conditions": {
                "missing_audience": null,
                "has_audience": null,
                "missing_scopes": [
                  "profile"
                ],
                "has_scopes": null
              }
            }
          ],
          "request": {
            "empty_audience": false,
            "scopes": null,
            "empty_scopes": false,
            "audience": null
          }
        },
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

다음 플레이스홀더는 반드시 여러분의 값으로 교체하세요:

  • region: 여러분의 Kong Konnect가 호스팅되고 운영되는 지리적 지역이에요.

  • KONNECT_TOKEN: Konnect 계정과 연결된 여러분의 Personal Access Token(PAT)이에요.

  • controlPlaneId: 컨트롤 플레인의 id예요.

지역별 URL과 personal access token에 대해 자세히 알아보려면 Konnect Control Planes Config API 레퍼런스를 확인하세요.

KIC
echo "
apiVersion: configuration.konghq.com/v1
kind: KongClusterPlugin
metadata:
  name:
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
  labels:
    global: 'true'
config:
  issuer: '$ISSUER'
  client_id:
  - '$CLIENT_ID'
  client_secret:
  - '$CLIENT_SECRET'
  client_auth:
  - client_secret_post
  auth_methods:
  - bearer
  token_exchange:
    subject_token_issuers:
    - issuer: '$ISSUER'
      conditions:
        missing_audience:
        has_audience:
        missing_scopes:
        - profile
        has_scopes:
    request:
      empty_audience: false
      scopes:
      empty_scopes: false
      audience:
  cache_tokens_salt: '$TOKEN_SALT'
plugin: openid-connect
" | kubectl apply -f -
Terraform
사전 준비: Personal Access Token 설정
terraform {
  required_providers {
    konnect = {
      source  = "kong/konnect"
    }
  }
}

provider "konnect" {
  personal_access_token = "$KONNECT_TOKEN"
  server_url            = "https://us.api.konghq.com/"
}

Konnect Gateway Plugin을 생성하려면 Terraform 구성에 다음을 추가하세요:

resource "konnect_gateway_plugin_openid_connect" "my_openid_connect" {
  enabled = true

  config = {
    issuer = var.issuer
    client_id = [var.client_id]
    client_secret = [var.client_secret]
    client_auth = ["client_secret_post"]
    auth_methods = ["bearer"]

    token_exchange = {
      subject_token_issuers = [
        {
          issuer = var.issuer

          conditions = {
            missing_audience = 
            has_audience = 
            missing_scopes = ["profile"]
            has_scopes = 
          }
        }      ]

      request = {
        empty_audience = false
        scopes = 
        empty_scopes = false
        audience = 
      }
    }
    cache_tokens_salt = var.token_salt
  }

  control_plane_id = konnect_gateway_control_plane.my_konnect_cp.id
}

이 예제에서는 다음 변수들을 매니페스트에 추가해야 해요. TF_VAR_name=value 형식으로 설정하면 런타임에 값을 지정할 수 있어요.

variable "issuer" {
  type = string
}
variable "client_id" {
  type = string
}
variable "client_secret" {
  type = string
}
variable "token_salt" {
  type = string
}

서비스

decK

다음 섹션을 kong.yaml 설정 파일에 추가하세요:

_format_version: "3.0"
plugins:
  - name: openid-connect
    service: serviceName|Id
    config:
      issuer: ${{ env "DECK_ISSUER" }}
      client_id:
      - ${{ env "DECK_CLIENT_ID" }}
      client_secret:
      - ${{ env "DECK_CLIENT_SECRET" }}
      client_auth:
      - client_secret_post
      auth_methods:
      - bearer
      token_exchange:
        subject_token_issuers:
        - issuer: ${{ env "DECK_ISSUER" }}
          conditions:
            missing_audience:
            has_audience:
            missing_scopes:
            - profile
            has_scopes:
        request:
          empty_audience: false
          scopes:
          empty_scopes: false
          audience:
      cache_tokens_salt: ${{ env "DECK_TOKEN_SALT" }}

{: data-file="kong.yaml" data-tool="deck" }

다음 플레이스홀더는 반드시 여러분의 값으로 교체하세요:

  • serviceName|Id: 플러그인 구성이 대상으로 할 서비스의 id 또는 name이에요.
Admin API

다음 요청을 보내세요:

curl -i -X POST http://localhost:8001/services/{serviceName|Id}/plugins/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "name": "openid-connect",
      "config": {
        "issuer": "'$ISSUER'",
        "client_id": [
          "'$CLIENT_ID'"
        ],
        "client_secret": [
          "'$CLIENT_SECRET'"
        ],
        "client_auth": [
          "client_secret_post"
        ],
        "auth_methods": [
          "bearer"
        ],
        "token_exchange": {
          "subject_token_issuers": [
            {
              "issuer": "'$ISSUER'",
              "conditions": {
                "missing_audience": null,
                "has_audience": null,
                "missing_scopes": [
                  "profile"
                ],
                "has_scopes": null
              }
            }
          ],
          "request": {
            "empty_audience": false,
            "scopes": null,
            "empty_scopes": false,
            "audience": null
          }
        },
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

다음 플레이스홀더는 반드시 여러분의 값으로 교체하세요:

  • serviceName|Id: 플러그인 구성이 대상으로 할 서비스의 id 또는 name이에요.
Konnect API

다음 요청을 보내세요:

curl -X POST https://{region}.api.konghq.com/v2/control-planes/{controlPlaneId}/core-entities/services/{serviceId}/plugins/ \
    --header "accept: application/json" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer $KONNECT_TOKEN" \
    --data '
    {
      "name": "openid-connect",
      "config": {
        "issuer": "'$ISSUER'",
        "client_id": [
          "'$CLIENT_ID'"
        ],
        "client_secret": [
          "'$CLIENT_SECRET'"
        ],
        "client_auth": [
          "client_secret_post"
        ],
        "auth_methods": [
          "bearer"
        ],
        "token_exchange": {
          "subject_token_issuers": [
            {
              "issuer": "'$ISSUER'",
              "conditions": {
                "missing_audience": null,
                "has_audience": null,
                "missing_scopes": [
                  "profile"
                ],
                "has_scopes": null
              }
            }
          ],
          "request": {
            "empty_audience": false,
            "scopes": null,
            "empty_scopes": false,
            "audience": null
          }
        },
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

다음 플레이스홀더는 반드시 여러분의 값으로 교체하세요:

  • region: 여러분의 Kong Konnect가 호스팅되고 운영되는 지리적 지역이에요.

  • KONNECT_TOKEN: Konnect 계정과 연결된 여러분의 Personal Access Token(PAT)이에요.

  • controlPlaneId: 컨트롤 플레인의 id예요.

  • serviceId: 플러그인 구성이 대상으로 할 서비스의 id예요.

지역별 URL과 personal access token에 대해 자세히 알아보려면 Konnect Control Planes Config API 레퍼런스를 확인하세요.

KIC
echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name:
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  issuer: '$ISSUER'
  client_id:
  - '$CLIENT_ID'
  client_secret:
  - '$CLIENT_SECRET'
  client_auth:
  - client_secret_post
  auth_methods:
  - bearer
  token_exchange:
    subject_token_issuers:
    - issuer: '$ISSUER'
      conditions:
        missing_audience:
        has_audience:
        missing_scopes:
        - profile
        has_scopes:
    request:
      empty_audience: false
      scopes:
      empty_scopes: false
      audience:
  cache_tokens_salt: '$TOKEN_SALT'
plugin: openid-connect
" | kubectl apply -f -

다음으로, service 리소스에 어노테이션을 추가해서 KongPlugin 리소스를 적용해요:

kubectl annotate -n kong service SERVICE_NAME konghq.com/plugins=
Terraform
사전 준비: 개인 액세스 토큰 구성하기
terraform {
  required_providers {
    konnect = {
      source  = "kong/konnect"
    }
  }
}

provider "konnect" {
  personal_access_token = "$KONNECT_TOKEN"
  server_url            = "https://us.api.konghq.com/"
}

Konnect Gateway 플러그인을 생성하려면 Terraform 구성에 다음 내용을 추가해요:

resource "konnect_gateway_plugin_openid_connect" "my_openid_connect" {
  enabled = true

  config = {
    issuer = var.issuer
    client_id = [var.client_id]
    client_secret = [var.client_secret]
    client_auth = ["client_secret_post"]
    auth_methods = ["bearer"]

    token_exchange = {
      subject_token_issuers = [
        {
          issuer = var.issuer

          conditions = {
            missing_audience = 
            has_audience = 
            missing_scopes = ["profile"]
            has_scopes = 
          }
        }      ]

      request = {
        empty_audience = false
        scopes = 
        empty_scopes = false
        audience = 
      }
    }
    cache_tokens_salt = var.token_salt
  }

  control_plane_id = konnect_gateway_control_plane.my_konnect_cp.id
  service = {
    id = konnect_gateway_service.my_service.id
  }
}

이 예제에서는 매니페스트에 다음 변수들을 추가해야 해요. TF_VAR_name=value 형식으로 값을 설정하면 런타임에 값을 지정할 수 있어요.

variable "issuer" {
  type = string
}
variable "client_id" {
  type = string
}
variable "client_secret" {
  type = string
}
variable "token_salt" {
  type = string
}

Route

decK

다음 섹션을 kong.yaml 구성 파일에 추가해요:

_format_version: "3.0"
plugins:
  - name: openid-connect
    route: routeName|Id
    config:
      issuer: ${{ env "DECK_ISSUER" }}
      client_id:
      - ${{ env "DECK_CLIENT_ID" }}
      client_secret:
      - ${{ env "DECK_CLIENT_SECRET" }}
      client_auth:
      - client_secret_post
      auth_methods:
      - bearer
      token_exchange:
        subject_token_issuers:
        - issuer: ${{ env "DECK_ISSUER" }}
          conditions:
            missing_audience:
            has_audience:
            missing_scopes:
            - profile
            has_scopes:
        request:
          empty_audience: false
          scopes:
          empty_scopes: false
          audience:
      cache_tokens_salt: ${{ env "DECK_TOKEN_SALT" }}

{: data-file="kong.yaml" data-tool="deck" }

다음 플레이스홀더는 꼭 여러분의 값으로 바꿔 주세요:

  • routeName|Id: 플러그인 구성의 대상이 될 라우트의 id 또는 name이에요.
Admin API

다음 요청을 보내세요:

curl -i -X POST http://localhost:8001/routes/{routeName|Id}/plugins/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "name": "openid-connect",
      "config": {
        "issuer": "'$ISSUER'",
        "client_id": [
          "'$CLIENT_ID'"
        ],
        "client_secret": [
          "'$CLIENT_SECRET'"
        ],
        "client_auth": [
          "client_secret_post"
        ],
        "auth_methods": [
          "bearer"
        ],
        "token_exchange": {
          "subject_token_issuers": [
            {
              "issuer": "'$ISSUER'",
              "conditions": {
                "missing_audience": null,
                "has_audience": null,
                "missing_scopes": [
                  "profile"
                ],
                "has_scopes": null
              }
            }
          ],
          "request": {
            "empty_audience": false,
            "scopes": null,
            "empty_scopes": false,
            "audience": null
          }
        },
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

다음 플레이스홀더는 꼭 여러분의 값으로 바꿔 주세요:

  • routeName|Id: 플러그인 구성의 대상이 될 라우트의 id 또는 name이에요.
Konnect API

다음 요청을 보내세요:

curl -X POST https://{region}.api.konghq.com/v2/control-planes/{controlPlaneId}/core-entities/routes/{routeId}/plugins/ \
    --header "accept: application/json" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer $KONNECT_TOKEN" \
    --data '
    {
      "name": "openid-connect",
      "config": {
        "issuer": "'$ISSUER'",
        "client_id": [
          "'$CLIENT_ID'"
        ],
        "client_secret": [
          "'$CLIENT_SECRET'"
        ],
        "client_auth": [
          "client_secret_post"
        ],
        "auth_methods": [
          "bearer"
        ],
        "token_exchange": {
          "subject_token_issuers": [
            {
              "issuer": "'$ISSUER'",
              "conditions": {
                "missing_audience": null,
                "has_audience": null,
                "missing_scopes": [
                  "profile"
                ],
                "has_scopes": null
              }
            }
          ],
          "request": {
            "empty_audience": false,
            "scopes": null,
            "empty_scopes": false,
            "audience": null
          }
        },
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

다음 플레이스홀더는 꼭 여러분의 값으로 바꿔 주세요:

  • region: 여러분의 Kong Konnect가 호스팅되고 운영되는 지리적 리전이에요.

  • KONNECT_TOKEN: Konnect 계정에 연결된 개인 액세스 토큰(PAT)이에요.

  • controlPlaneId: 컨트롤 플레인의 id예요.

  • routeId: 플러그인 구성의 대상이 될 라우트의 id예요.

리전별 URL과 개인 액세스 토큰에 대해 자세히 알아보려면 Konnect Control Planes Config API reference 문서를 확인하세요.

KIC
echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name:
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  issuer: '$ISSUER'
  client_id:
  - '$CLIENT_ID'
  client_secret:
  - '$CLIENT_SECRET'
  client_auth:
  - client_secret_post
  auth_methods:
  - bearer
  token_exchange:
    subject_token_issuers:
    - issuer: '$ISSUER'
      conditions:
        missing_audience:
        has_audience:
        missing_scopes:
        - profile
        has_scopes:
    request:
      empty_audience: false
      scopes:
      empty_scopes: false
      audience:
  cache_tokens_salt: '$TOKEN_SALT'
plugin: openid-connect
" | kubectl apply -f -

다음으로, httproute 또는 ingress 리소스에 어노테이션을 추가해서 KongPlugin 리소스를 적용해요:

Gateway API
kubectl annotate -n kong httproute  konghq.com/plugins=
Ingress
kubectl annotate -n kong ingress  konghq.com/plugins=
Terraform
사전 준비: 개인 액세스 토큰 구성하기
terraform {
  required_providers {
    konnect = {
      source  = "kong/konnect"
    }
  }
}

provider "konnect" {
  personal_access_token = "$KONNECT_TOKEN"
  server_url            = "https://us.api.konghq.com/"
}

Konnect Gateway 플러그인을 생성하려면 Terraform 구성에 다음 내용을 추가해요:

resource "konnect_gateway_plugin_openid_connect" "my_openid_connect" {
  enabled = true

  config = {
    issuer = var.issuer
    client_id = [var.client_id]
    client_secret = [var.client_secret]
    client_auth = ["client_secret_post"]
    auth_methods = ["bearer"]

    token_exchange = {
      subject_token_issuers = [
        {
          issuer = var.issuer

          conditions = {
            missing_audience = 
            has_audience = 
            missing_scopes = ["profile"]
            has_scopes = 
          }
        }      ]

      request = {
        empty_audience = false
        scopes = 
        empty_scopes = false
        audience = 
      }
    }
    cache_tokens_salt = var.token_salt
  }

  control_plane_id = konnect_gateway_control_plane.my_konnect_cp.id
  route = {
    id = konnect_gateway_route.my_route.id
  }
}

이 예제에서는 매니페스트에 다음 변수들을 추가해야 해요. TF_VAR_name=value 형식으로 값을 설정하면 런타임에 값을 지정할 수 있어요.

variable "issuer" {
  type = string
}
variable "client_id" {
  type = string
}
variable "client_secret" {
  type = string
}
variable "token_salt" {
  type = string
}

관련 리소스

더 알아보기 (Learn more)