Auth providers¶
Every auth method implements the same AuthProvider Protocol (headers() + refresh_if_needed()), so the rest of the client is identical regardless of what you pick.
The Protocol¶
base
¶
AuthProvider protocol for pluggable DHIS2 authentication.
Classes¶
AuthProvider
¶
Bases: Protocol
Injects authentication headers into outgoing DHIS2 requests.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/base.py
Basic¶
basic
¶
HTTP Basic authentication provider.
Classes¶
BasicAuth
¶
Bases: BaseModel
HTTP Basic auth — username/password encoded into Authorization header.
The password stays out of repr() (Field(repr=False)) and is masked in
model_dump(); pass context={"reveal": True} to model_dump() to reveal
it. headers() reads the plain attribute to build the Authorization header.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/basic.py
Personal Access Token¶
pat
¶
DHIS2 Personal Access Token authentication.
Classes¶
PatAuth
¶
Bases: BaseModel
DHIS2 Personal Access Token — sent as Authorization: ApiToken
The token stays out of repr() (Field(repr=False)) and is masked in
model_dump(); pass context={"reveal": True} to model_dump() to reveal
it. headers() reads the plain attribute to build the Authorization header.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/pat.py
OAuth2 / OIDC¶
oauth2
¶
OAuth 2.1 authorization-code flow with PKCE for DHIS2 OpenID Connect.
Attributes¶
RedirectCapturer = Callable[[str, str], Awaitable[str]]
module-attribute
¶
Callable signature for the redirect-receiver hook.
Takes (auth_url, expected_state) and returns the authorization code. The
default implementation calls capture_code() with sensible defaults; tests
and specialised callers (e.g. d2w profile verify's "don't open a
browser, just fail" probe) can inject their own implementation here.
DEFAULT_REDIRECT_PORT = 8765
module-attribute
¶
Loopback port the OAuth2 redirect receiver listens on by default.
DEFAULT_REDIRECT_URI = f'http://localhost:{DEFAULT_REDIRECT_PORT}'
module-attribute
¶
Canonical loopback redirect URI used by every CLI / service / example default.
Single source of truth so the port number doesn't drift across the six
profile / dev / sample / oauth2-registration call sites that previously
inlined "http://localhost:8765". Override via the matching --redirect-uri
flag (CLI) or redirect_uri keyword argument (service / library).
Classes¶
OAuth2Token
¶
Bases: BaseModel
Access + refresh token pair with expiry info (unix epoch seconds).
Both token values stay out of repr() (Field(repr=False)) and are masked
in model_dump(); pass context={"reveal": True} to model_dump() to
reveal them. Read the plain attributes when building an Authorization header
or a token-endpoint request body.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
TokenStore
¶
Bases: Protocol
Persists OAuth2 tokens across runs — filesystem, keyring, SQLite, etc.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
OAuth2Auth
¶
Authorization-code flow with PKCE against DHIS2 /oauth2/* endpoints.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | |
Functions¶
__init__(base_url, client_id, client_secret, scope, redirect_uri, token_store, store_key=None, redirect_capturer=None, open_browser=True, verify=True)
¶
Construct the provider.
store_key distinguishes tokens across profiles. redirect_capturer
is an optional callable (auth_url, expected_state) -> code that
replaces the default asyncio.start_server loopback implementation
— dhis2w-core injects a FastAPI-backed one here for a nicer UX.
open_browser=False skips the webbrowser.open() call in the
default capturer and prints the authorization URL to stderr for
copy-paste instead. Ignored when a custom redirect_capturer is
supplied — in that case, the caller owns the "how to get the URL
in front of the user" decision.
verify controls TLS certificate verification on the token-endpoint
calls (/oauth2/token). Pass the same value you pass to
Dhis2Client(verify=...) so the code exchange and refresh use the
same trust decision as the API traffic — False for self-signed
staging boxes, or a path to a custom CA bundle.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
headers()
async
¶
Return Authorization: Bearer
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
refresh_if_needed()
async
¶
Load cached token, refresh if close to expiry, run interactive flow if missing.
The whole check-refresh-persist section runs under an asyncio.Lock:
of N concurrent requests hitting an expired token, one refreshes (or
runs the interactive flow) while the rest wait and re-check, then
reuse the fresh token — a second concurrent refresh would submit an
already-rotated (revoked) refresh_token, and a second concurrent
first-time request would launch a duplicate browser flow. The token
store is written only when a new token was obtained, so the steady
state (valid cached token) costs zero store writes per request.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
Functions¶
capture_code(redirect_uri, expected_state, *, auth_url, open_browser=True, timeout=300.0)
async
¶
Listen on redirect_uri's host:port for the OAuth2 redirect; return code.
Bare asyncio.start_server — no FastAPI / uvicorn dependency. Validates
state and surfaces error / error_description query params raised
by the IdP. The browser sees a styled HTML confirmation page either
way.
auth_url is opened with webbrowser.open() once the server is
listening (skip with open_browser=False; URL is then printed to
stderr so the user can paste it into any browser). timeout bounds
the wait — raises OAuth2FlowError on timeout, state mismatch, or
IdP error.
Requests whose query string carries no code parameter (port scans,
browser preconnects, favicon fetches) get a 404 and are ignored — the
receiver keeps listening. Only a request that carries a code but a
wrong or missing state fails the flow.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/oauth2.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 140 141 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 167 168 169 170 171 172 173 174 175 176 | |
Session cookie¶
session
¶
DHIS2 session-cookie authentication.
Classes¶
SessionCookieAuth
¶
Bases: BaseModel
DHIS2 browser session — sent as a raw Cookie header (e.g. Cookie: JSESSIONID=
The cookie stays out of repr() (Field(repr=False)) and is masked in
model_dump(); pass context={"reveal": True} to model_dump() to reveal
it. headers() reads the plain attribute to build the Cookie header.
Source code in packages/dhis2w-client/src/dhis2w_client/v42/auth/session.py
Attributes¶
xsrf_token = Field(default=None, repr=False)
class-attribute
instance-attribute
¶
Double-submit CSRF token echoed as the X-XSRF-TOKEN header.
DHIS2 issues an XSRF-TOKEN cookie and expects it echoed back as the
X-XSRF-TOKEN header; None means the instance doesn't require CSRF, so
the header is omitted — inert by default. Masked like cookie.
Functions¶
headers()
async
¶
Return the raw Cookie header, plus X-XSRF-TOKEN when a CSRF token is set.