Skip to content

Authentication

Auth strategies implement the AuthStrategy protocol: async_authenticate() / authenticate() mutate the outgoing httpx.Request, and async_close() / close() release resources idempotently so a single strategy instance works with both async and sync clients.

Strategy Use case
NoAuth Public APIs (default)
StaticTokenAuth(token) Pre-issued bearer token
BasicAuth(username, password) HTTP Basic authentication (e.g. DataCite)
QueryParameterAuth(key_name, key_value) APIs authenticated by query parameter (OpenAlex api_key)
HeaderAuth(name, value) Static credential headers (Crossref Metadata Plus crossref-api-key)
ClientCredentialsAuth(client_id, client_secret, token_url, ...) OAuth2 client-credentials flow (Basic or POST body credentials, optional scope)
RefreshTokenAuth(token_url, refresh_token, ...) OAuth2 refresh-token flow with token caching and rotation

OAuth2 token caching and 401 refresh

ClientCredentialsAuth and RefreshTokenAuth fetch a bearer token, cache it using time.monotonic() until shortly before expires_in, serialize concurrent refreshes, and expose invalidate_token(). Pass user_agent=, scope=, timeout=, or a caller-owned http_client= as needed. For token endpoints that expect credentials in the form body rather than HTTP Basic (such as ORCID), pass token_auth_method="post" to ClientCredentialsAuth.

When a request receives HTTP 401 and the auth strategy exposes invalidate_token(), BaseApiClient invalidates the cached token and retries the request once before raising AuthError.

Missing or invalid credentials raise ConfigurationError; a failed token fetch raises AuthError.

from bibliofabric import ClientCredentialsAuth, RefreshTokenAuth

auth = ClientCredentialsAuth(
    client_id,
    client_secret,
    token_url,
    scope="/read-public",
    token_auth_method="post",
    user_agent=ua,
)
client = FooClient(auth=auth)

refresh_auth = RefreshTokenAuth(
    token_url,
    refresh_token,
    client_id=client_id,
    client_secret=client_secret,
)

Secret redaction

Auth strategies declare redacted_query_params: frozenset[str] and redacted_headers: frozenset[str] (empty by default). Built-in strategies populate these automatically (QueryParameterAuth redacts its key_name, HeaderAuth redacts its header name, and bearer/basic/OAuth2 strategies redact authorization), and BaseApiClient scrubs them from debug logs and exception messages.

API reference

bibliofabric.auth

Authentication strategies for bibliofabric-family clients.

A strategy mutates the outgoing httpx.Request in place (header or query parameter) and may hold resources closable through async_close() / close(). Strategies are shared by both client variants: one object works with an async client (async_authenticate) and a sync client (authenticate), so every strategy implements both method pairs.

AuthStrategy

Bases: Protocol

Applies credentials to an outgoing request, for both client variants.

Strategies may optionally expose redacted_query_params and redacted_headers (frozenset[str]) naming custom query parameters or headers whose values should be scrubbed from logs and error messages; when omitted, both default to empty sets. Token-caching strategies may also expose invalidate_token() -> None so BaseApiClient can refresh the token and retry once on HTTP 401.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class AuthStrategy(Protocol):
    """Applies credentials to an outgoing request, for both client variants.

    Strategies may optionally expose ``redacted_query_params`` and
    ``redacted_headers`` (``frozenset[str]``) naming custom query parameters
    or headers whose values should be scrubbed from logs and error messages;
    when omitted, both default to empty sets. Token-caching strategies may
    also expose ``invalidate_token() -> None`` so ``BaseApiClient`` can
    refresh the token and retry once on HTTP 401.
    """

    async def async_authenticate(self, request: httpx.Request) -> None:
        """Modify ``request`` to carry authentication information."""
        ...

    async def async_close(self) -> None:
        """Release underlying resources; must be idempotent."""
        ...

    def authenticate(self, request: httpx.Request) -> None:
        """Sync twin of :meth:`async_authenticate`."""
        ...

    def close(self) -> None:
        """Sync twin of :meth:`async_close`; must be idempotent."""
        ...

async_authenticate(request) async

Modify request to carry authentication information.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
55
56
57
async def async_authenticate(self, request: httpx.Request) -> None:
    """Modify ``request`` to carry authentication information."""
    ...

async_close() async

Release underlying resources; must be idempotent.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
59
60
61
async def async_close(self) -> None:
    """Release underlying resources; must be idempotent."""
    ...

authenticate(request)

Sync twin of :meth:async_authenticate.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
63
64
65
def authenticate(self, request: httpx.Request) -> None:
    """Sync twin of :meth:`async_authenticate`."""
    ...

close()

Sync twin of :meth:async_close; must be idempotent.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
67
68
69
def close(self) -> None:
    """Sync twin of :meth:`async_close`; must be idempotent."""
    ...

BasicAuth

Adds HTTP Basic authentication (Authorization: Basic <base64>).

Source code in packages/bibliofabric/src/bibliofabric/auth.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
class BasicAuth:
    """Adds HTTP Basic authentication (``Authorization: Basic <base64>``)."""

    redacted_query_params: frozenset[str] = frozenset()
    redacted_headers: frozenset[str] = frozenset({"authorization"})

    def __init__(self, username: str, password: str) -> None:
        if not username or not password:
            raise ConfigurationError(
                "BasicAuth requires a non-empty 'username' and 'password'."
            )
        encoded = base64.b64encode(f"{username}:{password}".encode()).decode("ascii")
        self._header_value = f"Basic {encoded}"

    async def async_authenticate(self, request: httpx.Request) -> None:
        request.headers["Authorization"] = self._header_value

    async def async_close(self) -> None:
        """Nothing to close."""

    def authenticate(self, request: httpx.Request) -> None:
        request.headers["Authorization"] = self._header_value

    def close(self) -> None:
        """Nothing to close."""

async_close() async

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
132
133
async def async_close(self) -> None:
    """Nothing to close."""

close()

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
138
139
def close(self) -> None:
    """Nothing to close."""

ClientCredentialsAuth

Bases: _OAuth2TokenAuth

OAuth2 client-credentials flow with an in-memory token cache.

Fetches a bearer token from token_url using client_id and client_secret and reuses it until shortly before expires_in. The cached token is shared by both client variants; each variant lazily creates its own httpx client for the token request (unless an external http_client is provided) and serializes its refreshes behind its own lock (asyncio.Lock for the async twin, threading.Lock for the sync twin). Set token_auth_method="post" for token endpoints (such as ORCID) that expect client_id and client_secret in the form body rather than an HTTP Basic header.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
class ClientCredentialsAuth(_OAuth2TokenAuth):
    """OAuth2 client-credentials flow with an in-memory token cache.

    Fetches a bearer token from ``token_url`` using ``client_id`` and
    ``client_secret`` and reuses it until shortly before ``expires_in``. The
    cached token is shared by both client variants; each variant lazily
    creates its own ``httpx`` client for the token request (unless an external
    ``http_client`` is provided) and serializes its refreshes behind its own
    lock (``asyncio.Lock`` for the async twin, ``threading.Lock`` for the sync
    twin). Set ``token_auth_method="post"`` for token endpoints (such as
    ORCID) that expect ``client_id`` and ``client_secret`` in the form body
    rather than an HTTP Basic header.
    """

    def __init__(
        self,
        client_id: str,
        client_secret: str,
        token_url: str,
        *,
        scope: str | None = None,
        token_auth_method: TokenAuthMethod = "basic",
        user_agent: str | None = None,
        timeout: float = 30.0,
        http_client: httpx.AsyncClient | httpx.Client | None = None,
    ) -> None:
        missing = [
            name
            for name, value in (
                ("client_id", client_id),
                ("client_secret", client_secret),
                ("token_url", token_url),
            )
            if not value
        ]
        if missing:
            raise ConfigurationError(
                f"ClientCredentialsAuth requires non-empty: {', '.join(missing)}."
            )
        if token_auth_method not in _VALID_TOKEN_AUTH_METHODS:
            raise ConfigurationError(
                "ClientCredentialsAuth token_auth_method must be 'basic' or 'post', "
                f"got {token_auth_method!r}."
            )
        super().__init__(
            token_url=token_url,
            user_agent=user_agent,
            timeout=timeout,
            http_client=http_client,
        )
        self._client_id = client_id
        self._client_secret = client_secret
        self._scope = scope
        self._token_auth_method = token_auth_method

    def _token_request_payload(self) -> tuple[httpx.Auth | None, dict[str, str]]:
        data: dict[str, str] = {"grant_type": "client_credentials"}
        if self._scope:
            data["scope"] = self._scope
        if self._token_auth_method == "post":
            data["client_id"] = self._client_id
            data["client_secret"] = self._client_secret
            return None, data
        return (
            httpx.BasicAuth(username=self._client_id, password=self._client_secret),
            data,
        )

HeaderAuth

Adds a static credential under a named header (e.g. Crossref Plus).

Source code in packages/bibliofabric/src/bibliofabric/auth.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
class HeaderAuth:
    """Adds a static credential under a named header (e.g. Crossref Plus)."""

    redacted_query_params: frozenset[str] = frozenset()

    def __init__(self, name: str, value: str) -> None:
        if not name or not value:
            raise ConfigurationError(
                "HeaderAuth requires a non-empty 'name' and 'value'."
            )
        self._name = name
        self._value = value
        self.redacted_headers: frozenset[str] = frozenset({name.lower()})

    async def async_authenticate(self, request: httpx.Request) -> None:
        request.headers[self._name] = self._value

    async def async_close(self) -> None:
        """Nothing to close."""

    def authenticate(self, request: httpx.Request) -> None:
        request.headers[self._name] = self._value

    def close(self) -> None:
        """Nothing to close."""

async_close() async

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
186
187
async def async_close(self) -> None:
    """Nothing to close."""

close()

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
192
193
def close(self) -> None:
    """Nothing to close."""

NoAuth

Strategy for APIs that need no authentication.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class NoAuth:
    """Strategy for APIs that need no authentication."""

    redacted_query_params: frozenset[str] = frozenset()
    redacted_headers: frozenset[str] = frozenset()

    async def async_authenticate(self, request: httpx.Request) -> None:
        """Do nothing."""

    async def async_close(self) -> None:
        """Nothing to close."""

    def authenticate(self, request: httpx.Request) -> None:
        """Do nothing."""

    def close(self) -> None:
        """Nothing to close."""

async_authenticate(request) async

Do nothing.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
78
79
async def async_authenticate(self, request: httpx.Request) -> None:
    """Do nothing."""

async_close() async

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
81
82
async def async_close(self) -> None:
    """Nothing to close."""

authenticate(request)

Do nothing.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
84
85
def authenticate(self, request: httpx.Request) -> None:
    """Do nothing."""

close()

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
87
88
def close(self) -> None:
    """Nothing to close."""

QueryParameterAuth

Adds the credential as a URL query parameter (e.g. OpenAlex api_key).

Source code in packages/bibliofabric/src/bibliofabric/auth.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class QueryParameterAuth:
    """Adds the credential as a URL query parameter (e.g. OpenAlex ``api_key``)."""

    redacted_headers: frozenset[str] = frozenset()

    def __init__(self, key_name: str, key_value: str) -> None:
        if not key_name or not key_value:
            raise ConfigurationError(
                "QueryParameterAuth requires a non-empty 'key_name' and 'key_value'."
            )
        self._key_name = key_name
        self._key_value = key_value
        self.redacted_query_params: frozenset[str] = frozenset({key_name})

    async def async_authenticate(self, request: httpx.Request) -> None:
        request.url = request.url.copy_merge_params({self._key_name: self._key_value})

    async def async_close(self) -> None:
        """Nothing to close."""

    def authenticate(self, request: httpx.Request) -> None:
        request.url = request.url.copy_merge_params({self._key_name: self._key_value})

    def close(self) -> None:
        """Nothing to close."""

async_close() async

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
159
160
async def async_close(self) -> None:
    """Nothing to close."""

close()

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
165
166
def close(self) -> None:
    """Nothing to close."""

RefreshTokenAuth

Bases: _OAuth2TokenAuth

OAuth2 refresh-token flow with an in-memory access-token cache.

Exchanges refresh_token at token_url for a bearer access token, caches it with time.monotonic() until shortly before expires_in, and updates the stored refresh token when the server rotates it.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
class RefreshTokenAuth(_OAuth2TokenAuth):
    """OAuth2 refresh-token flow with an in-memory access-token cache.

    Exchanges ``refresh_token`` at ``token_url`` for a bearer access token,
    caches it with ``time.monotonic()`` until shortly before ``expires_in``,
    and updates the stored refresh token when the server rotates it.
    """

    def __init__(
        self,
        token_url: str,
        refresh_token: str,
        *,
        client_id: str | None = None,
        client_secret: str | None = None,
        scope: str | None = None,
        user_agent: str | None = None,
        timeout: float = 30.0,
        http_client: httpx.AsyncClient | httpx.Client | None = None,
    ) -> None:
        missing = [
            name
            for name, value in (
                ("token_url", token_url),
                ("refresh_token", refresh_token),
            )
            if not value
        ]
        if missing:
            raise ConfigurationError(
                f"RefreshTokenAuth requires non-empty: {', '.join(missing)}."
            )
        if client_id is not None and not client_id:
            raise ConfigurationError(
                "RefreshTokenAuth 'client_id' must be non-empty when provided."
            )
        if client_secret is not None and not client_secret:
            raise ConfigurationError(
                "RefreshTokenAuth 'client_secret' must be non-empty when provided."
            )
        super().__init__(
            token_url=token_url,
            user_agent=user_agent,
            timeout=timeout,
            http_client=http_client,
        )
        self._refresh_token = refresh_token
        self._client_id = client_id
        self._client_secret = client_secret
        self._scope = scope

    def _token_request_payload(self) -> tuple[httpx.Auth | None, dict[str, str]]:
        data: dict[str, str] = {
            "grant_type": "refresh_token",
            "refresh_token": self._refresh_token,
        }
        if self._client_id is not None:
            data["client_id"] = self._client_id
        if self._client_secret is not None:
            data["client_secret"] = self._client_secret
        if self._scope:
            data["scope"] = self._scope
        return None, data

    def _store_token(
        self, payload: object, *, response: httpx.Response | None = None
    ) -> str:
        access_token = super()._store_token(payload, response=response)
        if isinstance(payload, dict):
            rotated = payload.get("refresh_token")
            if isinstance(rotated, str) and rotated:
                self._refresh_token = rotated
        return access_token

StaticTokenAuth

Adds Authorization: Bearer <token> to every request.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
class StaticTokenAuth:
    """Adds ``Authorization: Bearer <token>`` to every request."""

    redacted_query_params: frozenset[str] = frozenset()
    redacted_headers: frozenset[str] = frozenset({"authorization"})

    def __init__(self, token: str) -> None:
        if not token:
            raise ConfigurationError("StaticTokenAuth requires a non-empty 'token'.")
        self._token = token

    async def async_authenticate(self, request: httpx.Request) -> None:
        request.headers["Authorization"] = f"Bearer {self._token}"

    async def async_close(self) -> None:
        """Nothing to close."""

    def authenticate(self, request: httpx.Request) -> None:
        request.headers["Authorization"] = f"Bearer {self._token}"

    def close(self) -> None:
        """Nothing to close."""

async_close() async

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
105
106
async def async_close(self) -> None:
    """Nothing to close."""

close()

Nothing to close.

Source code in packages/bibliofabric/src/bibliofabric/auth.py
111
112
def close(self) -> None:
    """Nothing to close."""