Skip to content

Add JWT token authentication #717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Changes for crate

Unreleased
==========
- Added JWT token authentication

2025/01/30 2.0.0
================
Expand Down
6 changes: 6 additions & 0 deletions docs/connect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,12 @@ and password.
authenticate as the CrateDB superuser, which is ``crate``. The superuser
does not have a password, so you can omit the ``password`` argument.

Alternatively, authenticate using a JWT token:

>>> connection = client.connect(..., jwt_token="<JWT_TOKEN>")

Here, replace ``<JWT_TOKEN>`` with the appropriate JWT token.

.. _schema-selection:

Schema selection
Expand Down
4 changes: 4 additions & 0 deletions src/crate/client/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def __init__(
ssl_relax_minimum_version=False,
username=None,
password=None,
jwt_token=None,
schema=None,
pool_size=None,
socket_keepalive=True,
Expand Down Expand Up @@ -81,6 +82,8 @@ def __init__(
the username in the database.
:param password:
the password of the user in the database.
:param jwt_token:
the JWT token to authenticate with the server.
:param pool_size:
(optional)
Number of connections to save that can be reused.
Expand Down Expand Up @@ -148,6 +151,7 @@ def __init__(
ssl_relax_minimum_version=ssl_relax_minimum_version,
username=username,
password=password,
jwt_token=jwt_token,
schema=schema,
pool_size=pool_size,
socket_keepalive=socket_keepalive,
Expand Down
8 changes: 8 additions & 0 deletions src/crate/client/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ def request(
headers=None,
username=None,
password=None,
jwt_token=None,
schema=None,
backoff_factor=0,
**kwargs,
Expand All @@ -173,6 +174,10 @@ def request(
if length is not None:
headers["Content-Length"] = length

# Authentication token
if jwt_token is not None and "Authorization" not in headers:
headers["Authorization"] = "Bearer %s" % jwt_token

# Authentication credentials
if username is not None:
if "Authorization" not in headers and username is not None:
Expand Down Expand Up @@ -418,6 +423,7 @@ def __init__(
ssl_relax_minimum_version=False,
username=None,
password=None,
jwt_token=None,
schema=None,
pool_size=None,
socket_keepalive=True,
Expand Down Expand Up @@ -473,6 +479,7 @@ def __init__(
self._local = threading.local()
self.username = username
self.password = password
self.jwt_token = jwt_token
self.schema = schema

self.path = self.SQL_PATH
Expand Down Expand Up @@ -589,6 +596,7 @@ def _request(self, method, path, server=None, **kwargs):
path,
username=self.username,
password=self.password,
jwt_token=self.jwt_token,
backoff_factor=self.backoff_factor,
schema=self.schema,
**kwargs,
Expand Down
34 changes: 27 additions & 7 deletions tests/client/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,14 +571,22 @@
self.server.SHARED["schema"] = self.headers.get("Default-Schema")

if self.headers.get("Authorization") is not None:
auth_header = self.headers["Authorization"].replace("Basic ", "")
credentials = b64decode(auth_header).decode("utf-8").split(":", 1)
self.server.SHARED["username"] = credentials[0]
if len(credentials) > 1 and credentials[1]:
self.server.SHARED["password"] = credentials[1]
else:
self.server.SHARED["password"] = None
auth_header = self.headers["Authorization"]
if "Basic" in auth_header:
auth_header = auth_header.replace("Basic ", "")
credentials = (

Check warning on line 577 in tests/client/test_http.py

View check run for this annotation

Codecov / codecov/patch

tests/client/test_http.py#L574-L577

Added lines #L574 - L577 were not covered by tests
b64decode(auth_header).decode("utf-8").split(":", 1)
)
self.server.SHARED["username"] = credentials[0]
if len(credentials) > 1 and credentials[1]:
self.server.SHARED["password"] = credentials[1]

Check warning on line 582 in tests/client/test_http.py

View check run for this annotation

Codecov / codecov/patch

tests/client/test_http.py#L580-L582

Added lines #L580 - L582 were not covered by tests
else:
self.server.SHARED["password"] = None
elif "Bearer" in auth_header:
jwt_token = auth_header.replace("Bearer ", "")
self.server.SHARED["jwt_token"] = jwt_token

Check warning on line 587 in tests/client/test_http.py

View check run for this annotation

Codecov / codecov/patch

tests/client/test_http.py#L584-L587

Added lines #L584 - L587 were not covered by tests
else:
self.server.SHARED["jwt_token"] = None

Check warning on line 589 in tests/client/test_http.py

View check run for this annotation

Codecov / codecov/patch

tests/client/test_http.py#L589

Added line #L589 was not covered by tests
self.server.SHARED["username"] = None

if self.headers.get("X-User") is not None:
Expand All @@ -604,6 +612,7 @@
SHARED = manager.dict()
SHARED["count"] = 0
SHARED["usernameFromXUser"] = None
SHARED["jwt_token"] = None
SHARED["username"] = None
SHARED["password"] = None
SHARED["schema"] = None
Expand Down Expand Up @@ -689,13 +698,17 @@
def setUp(self):
super().setUp()
self.clientWithoutUsername = self.clientWithKwargs()
self.clientWithJwtToken = self.clientWithKwargs(
jwt_token="testJwtToken"
)
self.clientWithUsername = self.clientWithKwargs(username="testDBUser")
self.clientWithUsernameAndPassword = self.clientWithKwargs(
username="testDBUser", password="test:password"
)

def tearDown(self):
self.clientWithoutUsername.close()
self.clientWithJwtToken.close()
self.clientWithUsername.close()
self.clientWithUsernameAndPassword.close()
super().tearDown()
Expand All @@ -720,6 +733,13 @@
self.assertEqual(TestingHTTPServer.SHARED["username"], "testDBUser")
self.assertEqual(TestingHTTPServer.SHARED["password"], "test:password")

def test_jwt_token(self):
self.clientWithoutUsername.sql("select * from fake")
self.assertEqual(TestingHTTPServer.SHARED["jwt_token"], None)

self.clientWithJwtToken.sql("select * from fake")
self.assertEqual(TestingHTTPServer.SHARED["jwt_token"], "testJwtToken")


class TestCrateJsonEncoder(TestCase):
def test_naive_datetime(self):
Expand Down