JWT(JSON Web Token) 기반 토큰 인증
JWT(JSON Web Token) 기반 토큰 인증 (Authentication using tokens based on JSON Web Tokens)
Pulsar는 JSON Web Tokens (RFC-7519) 기반 보안 토큰으로 클라이언트를 인증하는 것을 지원해요. Java JWT 라이브러리가 지원하는 모든 알고리즘을 포함해요. 이번에는 JWT 토큰을 만들고 브로커/프록시 및 클라이언트에서 구성하는 방법을 함께 살펴볼게요.
출처: 문서
본문
토큰은 사용자와 연결된 자격 증명이에요. 그 연결은 "주체(principal)" 또는 "역할(role)"을 통해 이루어져요. JWT 토큰의 경우 보통 subject를 가리켜요. 토큰으로 Pulsar 클라이언트를 식별하고, 토픽에 메시지를 게시하거나 토픽에서 메시지를 소비하는 것 같은 특정 작업을 허용받는 subject와 연결할 수 있어요. 대안으로 "토큰 공급자(token supplier)"(클라이언트 라이브러리가 토큰이 필요할 때 토큰을 반환하는 함수)를 전달할 수도 있어요.
애플리케이션은 클라이언트 인스턴스를 만들 때 토큰을 지정해요. 사용자는 보통 관리자로부터 토큰 문자열을 받아요. 서명된 JWT의 압축 표현은 다음과 같은 문자열이에요.
eyJhbG...62SY
note 토큰을 보내는 것은 유선상으로 비밀번호를 보내는 것과 같으므로, Pulsar 서비스에 연결할 때는 항상 TLS 암호화를 사용해요.
클라이언트 인증서 만들기 (Create client certificates)
JWT 인증은 토큰을 생성·검증하기 위해 두 종류의 키를 지원해요.
- 대칭(Symmetric): 단일 비밀(secret) 키
- 비대칭(Asymmetric): 키 쌍, 다음 포함
- 토큰을 생성하는 개인(private) 키
- 토큰을 검증하는 공개(public) 키
비밀 키 만들기 (Create a secret key)
관리자가 비밀 키를 만들고 이를 사용해 클라이언트 토큰을 생성해요. 브로커가 클라이언트를 검증하도록 이 키를 구성할 수도 있어요.
다음 명령으로 비밀 키를 만들 수 있어요. 출력 파일은 Pulsar 설치 디렉터리의 루트에 생성돼요.
bin/pulsar tokens create-secret-key --output my-secret.key
다음 명령으로 출력 파일의 절대 경로를 제공할 수도 있어요.
bin/pulsar tokens create-secret-key --output /opt/my-secret.key
base64로 인코딩된 개인 키를 생성하려면 다음 명령을 입력해요.
bin/pulsar tokens create-secret-key --output my-secret.key --base64
키 쌍 만들기 (Create a key pair)
비대칭 키 암호화를 사용하려면 다음 명령으로 키 쌍을 만들어야 해요. 출력 파일은 Pulsar 설치 디렉터리의 루트에 생성돼요.
bin/pulsar tokens create-key-pair --output-private-key my-private.key --output-public-key my-public.key
my-private.key는 안전한 위치에 저장하고 관리자만 이 개인 키로 새 토큰을 생성할 수 있어요.- 공개 키 파일
my-public.key는 모든 Pulsar 브로커에 배포돼요. 보안 우려 없이 공개적으로 공유할 수 있어요.
토큰 생성 (Generate tokens)
- 다음 명령으로 생성된 토큰이 subject 필드를 가지도록 요구해요. 이 명령은 토큰 문자열을
stdout에 출력해요.
bin/pulsar tokens create --secret-key file:///path/to/my-secret.key \
--subject test-user
- 다음 명령으로 "private" 키를 전달해 토큰을 만들어요.
bin/pulsar tokens create --private-key file:///path/to/my-private.key \
--subject test-user
- 사전 정의된 TTL로 토큰을 만들어요. 그러면 그 시간이 지나면 토큰이 자동으로 무효화돼요.
bin/pulsar tokens create --secret-key file:///path/to/my-secret.key \
--subject test-user \
--expiry-time 1y
tip 토큰 자체에는 연결된 권한이 없어요. 권한 부여 활성화와 수퍼유저 지정을 수행하고,
bin/pulsar-admin namespaces grant-permission명령으로 토큰에 권한을 부여해야 해요.
브로커/프록시에서 JWT 인증 활성화 (Enable JWT authentication on brokers/proxies)
브로커/프록시가 JWT로 클라이언트를 인증하도록 구성하려면 conf/broker.conf와 conf/proxy.conf 파일에 다음 파라미터를 추가해요. standalone Pulsar를 사용한다면 conf/standalone.conf 파일에 이 파라미터를 추가해야 해요.
# Configuration to enable authentication
authenticationEnabled=true
authenticationProviders=org.apache.pulsar.broker.authentication.AuthenticationProviderToken
# Authentication settings of the broker itself. Used when the broker connects to other brokers, or when the proxy connects to brokers, either in same or other clusters
brokerClientAuthenticationPlugin=org.apache.pulsar.client.impl.auth.AuthenticationToken
brokerClientAuthenticationParameters={"token":"eyJhbG...SxXw"}
# Either configure the token string or specify to read it from a file. The following three available formats are all valid:
# brokerClientAuthenticationParameters={"token":"your-token-string"}
# brokerClientAuthenticationParameters=token:your-token-string
# brokerClientAuthenticationParameters=file:///path/to/token
# If using secret key (Note: key files must be DER-encoded)
tokenSecretKey=file:///path/to/secret.key
# The key can also be passed inline:
# tokenSecretKey=data:;base64,FLFyW0oLJ2Fi22KKCm21J18mbAdztfSHN/lAT5ucEKU=
# If using public/private (Note: key files must be DER-encoded)
# tokenPublicKey=file:///path/to/public.key
CLI 도구에서 JWT 인증 구성 (Configure JWT authentication in CLI Tools)
pulsar-admin, pulsar-perf, pulsar-client 같은 커맨드라인 도구는 Pulsar 설치의 conf/client.conf 구성 파일을 사용해요.
Pulsar의 CLI 도구와 JWT 인증을 사용하려면 conf/client.conf 구성 파일에 다음 파라미터를 추가해야 해요.
webServiceUrl=https://broker.example.com:8443/
brokerServiceUrl=pulsar://broker.example.com:6650/
authPlugin=org.apache.pulsar.client.impl.auth.AuthenticationToken
authParams=token:eyJhbG...62SY
토큰 문자열을 파일에서 읽을 수도 있어요. 예:
authParams=file:///path/to/token/file
Pulsar 클라이언트에서 JWT 인증 구성 (Configure JWT authentication in Pulsar clients)
토큰으로 다음 Pulsar 클라이언트를 인증할 수 있어요.
- Java
- Python
- Go
- C++
- C#
Java:
PulsarClient client = PulsarClient.builder()
.serviceUrl("pulsar://broker.example.com:6650/")
.authentication(
AuthenticationFactory.token("eyJhbG...62SY"))
.build();
유사하게 Supplier를 전달할 수도 있어요.
PulsarClient client = PulsarClient.builder()
.serviceUrl("pulsar://broker.example.com:6650/")
.authentication(
AuthenticationFactory.token(() -> {
// Read token from custom source
return readToken();
}))
.build();
Python:
from pulsar import Client, AuthenticationToken
client = Client('pulsar://broker.example.com:6650/',
authentication=AuthenticationToken('eyJhbG...62SY'))
대안으로 Supplier를 전달할 수도 있어요.
def read_token():
with open('/path/to/token.txt') as tf:
return tf.read().strip()
client = Client('pulsar://broker.example.com:6650/',
authentication=AuthenticationToken(read_token))
Go:
client, err := pulsar.NewClient(pulsar.ClientOptions{
URL: "pulsar://localhost:6650",
Authentication: NewAuthenticationToken("eyJhbG...62SY"),
})
유사하게 Supplier를 전달할 수도 있어요.
client, err := pulsar.NewClient(pulsar.ClientOptions{
URL: "pulsar://localhost:6650",
Authentication: pulsar.NewAuthenticationTokenSupplier(func () string {
// Read token from custom source
return readToken()
}),
})
C++:
#include <pulsar/Client.h>
pulsar::ClientConfiguration config;
config.setAuth(pulsar::AuthToken::createWithToken("eyJhbG...62SY"));
pulsar::Client client("pulsar://broker.example.com:6650/", config);
C#:
var client = PulsarClient.Builder()
.AuthenticateUsingToken("eyJhbG...62SY")
.Build();
더 알아보기 (Learn more)
- 인증의 기본 개념은 Security overview 문서에서 확인해요.
- 권한 부여 설정은 Authorization 문서를 참고해요.
- 토큰 관리 명령은 Token authentication admin 문서를 봐요.
- 토큰을 안전하게 보내려면 TLS transport 문서를 살펴봐요.