Authentication
Authentication turns a root Client into an authenticated client. Use the root
client to choose the KSeF environment, then choose exactly one authentication
method for the context you are operating as.
Environment variables
Section titled “Environment variables”These names are used by examples in this documentation and by ksef2-cli
profiles:
| Variable | Purpose |
|---|---|
KSEF2_ENV | test, demo, or production for SDK examples. |
KSEF2_NIP | Taxpayer/context NIP used during authentication. |
KSEF2_TOKEN | KSeF token for token authentication. |
KSEF2_PROFILE | CLI profile name selected by ksef2-cli and SDK profile auth. |
KSEF2_CONFIG | Optional path to the CLI profile config file. |
KSEF2_KEY_PASSWORD | Optional encrypted PEM private-key password. |
KSEF2_P12_PASSWORD | Optional PKCS#12/PFX archive password. |
export KSEF2_ENV=testexport KSEF2_NIP=5261040828export KSEF2_TOKEN=replace-with-a-real-ksef-tokenThe SDK reads KSEF2_PROFILE and KSEF2_CONFIG when you use
client.authentication.with_profile(). For direct token or certificate auth,
keep the boundary explicit in your application:
import os
from ksef2 import Client, Environment
environment_name = os.environ.get("KSEF2_ENV", "test").upper()client = Client(Environment[environment_name])Choose an authentication method
Section titled “Choose an authentication method”Use a KSeF token when your application already has a valid token for the context. Token auth works in TEST, DEMO, and PRODUCTION.
import os
auth = client.authentication.with_token( ksef_token=os.environ["KSEF2_TOKEN"], nip=os.environ["KSEF2_NIP"], context_type="nip",)Use the SDK-generated TEST certificate for local development. This method is
only available with Environment.TEST.
import os
auth = client.authentication.with_test_certificate( nip=os.environ["KSEF2_NIP"],)Use PEM certificate and private-key files when your certificate material is stored separately.
import os
from ksef2.core.xades import load_certificate_from_pem, load_private_key_from_pem
password = os.environ.get("KSEF2_KEY_PASSWORD")cert = load_certificate_from_pem("company.pem")private_key = load_private_key_from_pem( "company.key", password=password.encode() if password else None,)
auth = client.authentication.with_xades( nip=os.environ["KSEF2_NIP"], cert=cert, private_key=private_key,)Use a PKCS#12/PFX archive when the certificate and private key are stored in one file.
import os
from ksef2.core.xades import load_certificate_and_key_from_p12
password = os.environ.get("KSEF2_P12_PASSWORD")cert, private_key = load_certificate_and_key_from_p12( "company.p12", password=password.encode() if password else None,)
auth = client.authentication.with_xades( nip=os.environ["KSEF2_NIP"], cert=cert, private_key=private_key,)CLI-compatible profiles
Section titled “CLI-compatible profiles”ksef2-cli already has local profile support. A profile stores non-secret
defaults such as environment, NIP, auth method, certificate paths, and the name
of the environment variable that contains a secret.
ksef2 profile create test-company \ --env test \ --nip 5261040828 \ --test-cert
ksef2 profile create prod-token \ --env production \ --nip "$KSEF2_NIP" \ --token-env KSEF2_TOKENSelect a profile for CLI commands:
export KSEF2_PROFILE=prod-tokenksef2 profile currentUse the same profile file from SDK code:
from ksef2 import Client, Environmentfrom ksef2.profiles import Profile, ProfileStore, TokenProfileAuth
store = ProfileStore.default()store.save( "prod-token", Profile( environment=Environment.PRODUCTION, nip="5261040828", auth=TokenProfileAuth(token_env="KSEF2_TOKEN"), ), activate=True, overwrite=True,)
client = Client(Environment.PRODUCTION)auth = client.authentication.with_profile()
# Or select a named profile explicitly.auth = client.authentication.with_profile("prod-token")The root client environment must match the selected profile environment. Pass
config_path="..." when the profile file is not at the default
~/.config/ksef2-cli/config.toml location.
Recommended flow
Section titled “Recommended flow”-
Put secrets into environment variables.
Use
KSEF2_TOKEN,KSEF2_KEY_PASSWORD, orKSEF2_P12_PASSWORD. -
Keep non-secret defaults in one place.
Use application config for fully custom setups, or
ksef2-cliprofiles when the same environment is also operated from the command line. -
Create the root client for the selected environment.
Use
Client(Environment.TEST),Client(Environment.DEMO), orClient(Environment.PRODUCTION). -
Authenticate once, then pass the authenticated client into workflows.
The authenticated client owns access tokens and exposes workflow branches.
Errors
Section titled “Errors”Catch SDK-classified failures with KSeFException. Catch httpx.HTTPError
separately for transport failures before KSeF returns a response.
import httpx
from ksef2 import KSeFException
try: auth = client.authentication.with_test_certificate(nip="5261040828")except KSeFException as exc: print(exc)except httpx.HTTPError as exc: print(f"Transport failed: {exc}")