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

OpenID Connect: 인가 코드 플로우

원문 보기 위키 갱신

OpenID Connect: 인가 코드 플로우 (Authorization Code Flow)

이 문서는 Kong Gateway에서 OpenID Connect 플러그인을 인가 코드 플로우 방식으로 설정하는 방법을 다뤄요. 클라이언트가 IdP에서 인가 코드를 받고, Kong이 토큰을 검증한 뒤 세션 쿠키로 인증 요청을 처리하는 전체 흐름을 다이어그램과 함께 설명해요. 사전 준비 사항과 환경 변수, 플러그인 설정 방법, 그리고 Keycloak을 활용한 전체 예제 링크까지 안내해요.

출처: 문서

본문

권한 부여 코드 플로우v1.0+

이 예제는 OpenID Connect 플러그인을 권한 부여 코드 플로우로 구성해요.

권한 부여 코드 플로우가 작동하는 방식은 다음과 같아요:

 
sequenceDiagram
    autonumber
    participant client as Client 
(e.g. mobile app) participant kong as Gateway participant idp as IdP
(e.g. Keycloak) participant httpbin as Upstream
(upstream service,
e.g. httpbin) activate client activate kong client->>kong: HTTP request kong->>client: Redirect mobile app to IDP deactivate kong activate idp client->>idp: Request access and authentication
with client parameter Note left of idp: /auth
response_type=code,
scope=openid idp->>client: Login (ask for consent) client->>idp: /auth with user credentials (grant consent) idp->>client: Return authorization code and redirect Note left of idp: short-lived authcode activate kong client->>kong: HTTP redirect with authorization code deactivate client kong->>kong: Verify authorization code flow kong->>idp: Request ID token, access token, and refresh token Note left of idp: /token
client_id:client_secret
authcode idp->>idp: Authenticate client (Kong)
and validate authcode idp->>kong: Returns tokens Note left of idp: ID token, access token, and refresh token deactivate idp kong->>kong: Validate tokens Note right of kong: Cryptographic
signature validation,
expiry check
(OIDC Standard JWT validation) activate client kong->>client: Redirect with session cookie
having session ID (SID) Note left of kong: sid: cryptorandom bytes
(128 bits)
& HMAC protected client->>kong: Authenticated request with session cookie deactivate client kong->>kong: Verify session cookie Note right of kong: Retrieve encrypted tokens
from session store (redis) activate httpbin kong->>httpbin: Backend service request with tokens Note right of idp: Access token and ID token httpbin->>kong: Backend service response deactivate httpbin activate client kong->>client: HTTP response deactivate kong deactivate client

Keycloak으로 권한 부여 코드 플로우를 설정하는 방법을 보여주는 전체 예제는 권한 부여 코드 플로우로 OpenID Connect 구성하기를 참고하세요.

참고: config.client_auth를 client_secret_post로 설정하면 IdP와의 연결을 테스트할 수 있지만, 프로덕션에서는 더 안전한 인증 방법을 사용하는 걸 추천해요. 지원되는 클라이언트 인증 방법 중 어떤 것이든 사용할 수 있어요.

전제 조건

  • 구성된 ID 공급자(IdP)

환경 변수

  • ISSUER: IdP의 issuer 인증 URL이에요. 예를 들어, Keycloak을 IdP로 사용한다면 issuer URL은 다음과 같아요: http://localhost:8080/realms/example-realm

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

  • CLIENT_SECRET: IdP에 연결하는 데 필요한 클라이언트 시크릿이에요.

  • 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:
      - authorization_code
      - session
      response_mode: form_post
      preserve_query_args: true
      login_action: redirect
      login_tokens:
      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": [
          "authorization_code",
          "session"
        ],
        "response_mode": "form_post",
        "preserve_query_args": true,
        "login_action": "redirect",
        "login_tokens": 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": [
          "authorization_code",
          "session"
        ],
        "response_mode": "form_post",
        "preserve_query_args": true,
        "login_action": "redirect",
        "login_tokens": null,
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

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

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

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

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

지역별 URL과 개인 액세스 토큰에 대해 자세히 알아보려면 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:
  - authorization_code
  - session
  response_mode: form_post
  preserve_query_args: true
  login_action: redirect
  login_tokens:
  cache_tokens_salt: '$TOKEN_SALT'
plugin: openid-connect
" | kubectl apply -f -
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 = ["authorization_code", "session"]
    response_mode = "form_post"
    preserve_query_args = true
    login_action = "redirect"
    login_tokens = 
    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:
      - authorization_code
      - session
      response_mode: form_post
      preserve_query_args: true
      login_action: redirect
      login_tokens:
      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": [
          "authorization_code",
          "session"
        ],
        "response_mode": "form_post",
        "preserve_query_args": true,
        "login_action": "redirect",
        "login_tokens": 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": [
          "authorization_code",
          "session"
        ],
        "response_mode": "form_post",
        "preserve_query_args": true,
        "login_action": "redirect",
        "login_tokens": null,
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

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

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

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

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

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

리전별 URL과 개인 액세스 토큰에 대해 알아보려면 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:
  - authorization_code
  - session
  response_mode: form_post
  preserve_query_args: true
  login_action: redirect
  login_tokens:
  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 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 = ["authorization_code", "session"]
    response_mode = "form_post"
    preserve_query_args = true
    login_action = "redirect"
    login_tokens = 
    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
}

라우트

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:
      - authorization_code
      - session
      response_mode: form_post
      preserve_query_args: true
      login_action: redirect
      login_tokens:
      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": [
          "authorization_code",
          "session"
        ],
        "response_mode": "form_post",
        "preserve_query_args": true,
        "login_action": "redirect",
        "login_tokens": 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": [
          "authorization_code",
          "session"
        ],
        "response_mode": "form_post",
        "preserve_query_args": true,
        "login_action": "redirect",
        "login_tokens": null,
        "cache_tokens_salt": "'$TOKEN_SALT'"
      }
    }
    '

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

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

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

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

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

리전별 URL과 개인 액세스 토큰에 대해 자세히 알아보려면 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:
  - authorization_code
  - session
  response_mode: form_post
  preserve_query_args: true
  login_action: redirect
  login_tokens:
  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 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 = ["authorization_code", "session"]
    response_mode = "form_post"
    preserve_query_args = true
    login_action = "redirect"
    login_tokens = 
    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)