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

WebSocket 요청에 OAuth 2.0 인증 활성화

원문 보기 위키 갱신

WebSocket 요청에 OAuth 2.0 인증 활성화 (Enable OAuth 2.0 authentication for WebSocket requests)

WebSocket Route에서는 OAuth 2.0 Authentication 플러그인이 새 토큰을 직접 발급하지 못해요. 그래서 토큰 발급을 담당할 별도의 HTTP Service와 Route를 만들고, WebSocket Service와 HTTP Route 양쪽에 플러그인을 활성화한 뒤 config.global_credentials를 true로 설정해야 해요. 이 튜토리얼에서는 decK를 사용해 provision key 발급부터 플러그인 설정, Consumer와 애플리케이션 생성, 토큰 발급과 검증까지 전 과정을 단계별로 안내해요

출처: 문서

본문

TL;DR

WebSocket Service에 OAuth 2.0을 어떻게 설정하나요? OAuth 2.0 Authentication 플러그인은 WebSocket Route에서 새 토큰을 발급할 수 없기 때문에, 토큰 생성을 처리할 별도의 HTTP Service와 Route를 만들어야 해요. WebSocket Service와 HTTP Route 양쪽 모두에서 플러그인을 활성화하고, config.global_credentials를 true로 설정하는 것을 잊지 마세요.

전제 조건

Kong Gateway 실행 중

이 튜토리얼에는 Kong Gateway Enterprise가 필요해요. 아직 Kong Gateway를 설정하지 않았다면, 엔터프라이즈 라이선스와 함께 quickstart 스크립트를 사용해서 거의 즉시 Kong Gateway 인스턴스를 실행할 수 있어요.

  1. 라이선스를 환경 변수로 내보내세요:

    export KONG_LICENSE_DATA='LICENSE-CONTENTS-GO-HERE'
    
  2. quickstart 스크립트를 실행하세요:

    curl -Ls https://get.konghq.com/quickstart | bash -s -- -e KONG_LICENSE_DATA 
    

    Kong Gateway가 준비되면 다음 메시지가 표시돼요:

    Kong Gateway Ready
    

    {:.no-copy-code}

decK   v1.68.0+

이 튜토리얼을 완료하려면 decK를 설치하세요. decK는 항상 최신 버전(1.68.0)을 유지하는 것을 추천해요.

decK는 상태 파일을 사용해 Kong Gateway를 선언적으로 관리하는 CLI 도구예요. 이 가이드에서는 엔티티 구성을 Gateway 인스턴스에 직접 적용하는 deck gateway apply를 사용해요.

deck version으로 현재 decK 버전을 확인할 수 있어요.

필수 엔티티

이 튜토리얼에서는 Gateway Services와 Routes 같은 Kong Gateway 엔티티가 미리 구성되어 있어야 해요. 이 엔티티들은 Kong Gateway가 동작하는 데 필수적이지만, 이를 설치하는 것이 이 가이드의 초점은 아니에요. 다음 단계에 따라 미리 구성하세요:

  1. 다음 명령어를 실행하세요:

    echo '
    _format_version: "3.0"
    services:
      - name: example-websocket-service
        url: ws://echo.websocket.org/
    routes:
      - name: example-websocket-route
        paths:
        - "/anything"
        protocols:
        - ws
        service:
          name: example-websocket-service
    ' | deck gateway apply -
    

    {: data-test-prereq="block" }

엔티티에 대해 더 자세히 알아보려면 엔티티 문서를 읽어보세요.

토큰 생성을 처리할 HTTP Service와 Route 만들기

전제 조건에서 WebSocket Service와 Route를 만들었어요.

OAuth 2.0 Authentication 플러그인을 WebSocket 서비스와 함께 사용하려면, 토큰을 발급할 추가적인 non-WebSocket Route가 필요해요:

echo '
_format_version: "3.0"
routes:
  - name: websocket-token-route
    protocols:
    - https
    paths:
    - "/token-route"
    methods:
    - POST
' | deck gateway apply -

{: data-test-step="block" }

프로비전 키 생성하기

uuidgen을 사용해서 OAuth 2.0 Authentication 플러그인의 프로비전 키를 생성하세요:

export DECK_PROVISION_KEY="$(uuidgen)"

OAuth 2.0 플러그인 활성화하기

다음 대상에 플러그인을 활성화하세요:

  • 보안을 위해 전제 조건에서 만든 WebSocket Gateway Service
  • 토큰 생성을 활성화하기 위한 HTTP Route

다른 플러그인 인스턴스가 생성한 토큰을 허용하려면 config.global_credentials를 true로 설정하세요.

echo '
_format_version: "3.0"
plugins:
  - name: oauth2
    service: example-websocket-service
    config:
      scopes:
      - email
      - profile
      global_credentials: true
      provision_key: "${{ env "DECK_PROVISION_KEY" }}"
      enable_client_credentials: true
  - name: oauth2
    route: websocket-token-route
    config:
      scopes:
      - email
      - profile
      global_credentials: true
      provision_key: "${{ env "DECK_PROVISION_KEY" }}"
      enable_client_credentials: true
' | deck gateway apply -

{: data-test-step="block" }

Consumer 만들기

Consumer를 사용하면 Kong Gateway와 상호작용하는 클라이언트를 식별할 수 있어요. username만으로 새로운 Consumer를 만드세요:

echo '
_format_version: "3.0"
consumers:
  - username: alex
' | deck gateway apply -

{: data-test-step="block" }

애플리케이션 만들기

Consumer를 위한 애플리케이션을 만드세요:

curl -X POST "http://localhost:8001/consumers/alex/oauth2" \
     --no-progress-meter --fail-with-body  \
     -H "Accept: application/json"\
     -H "Content-Type: application/json" \
     --json '{
       "name": "TestApp",
       "redirect_uris": [
         "http://localhost:8000/anything"
       ]
     }'

자동 생성된 client ID와 client secret을 환경 변수로 내보내세요:

export CLIENT_ID={client_id}
export CLIENT_SECRET={client_secret}

토큰 생성하기

애플리케이션의 client credentials를 사용해서 토큰을 생성하세요:

curl -X POST "https://localhost:8443/token-route/oauth2/token" \
  --header "Content-Type: application/json" \
  --json '{ 
    "client_id": "'$CLIENT_ID'", 
    "client_secret": "'$CLIENT_SECRET'", 
    "grant_type": "client_credentials" 
  }'

참고: 이 요청에는 HTTPS가 필요하기 때문에 8000 대신 8443 포트를 사용해야 해요.

검증하기

구성이 기대한 대로 동작하는지 검증하려면, 생성한 Bearer 토큰을 Authorization 헤더에 담아 ws://localhost:8000/anything으로 WebSocket 연결을 여세요. 이 작업은 Insomnia를 사용해서 할 수 있어요.

정리

Konnect 환경 정리하기

새 control plane을 만들었고 무료 체험 크레딧을 아끼거나 불필요한 비용을 피하고 싶다면, 이 튜토리얼에서 사용한 새 control plane을 삭제하세요.

Kong Gateway 컨테이너 삭제하기

curl -Ls https://get.konghq.com/quickstart | bash -s -- -d

관련 리소스

더 알아보기 (Learn more)

  • WebSocket 서비스에 적용하는 OAuth 2.0 플러그인의 개요와 설정 방법 안내 — OAuth 2.0 Authentication
  • 이 튜토리얼에서 true로 설정하는 핵심 옵션의 스키마 설명 — config.global_credentials
  • 토큰을 발급받을 애플리케이션을 만들 때 필요한 Consumer 엔티티 설명 — Consumers
  • 가이드 전반에서 엔티티를 선언형으로 적용할 때 사용하는 decK CLI 도구 소개 — decK
  • Service와 Route 같은 Kong Gateway 엔티티의 기본 개념 정리 — entities documentation