KSeF Connection & Authentication
KSeF uses a token-based authentication model issued by the Ministry of Finance. This page explains the full authentication flow, what happens during a KSeF session, and how to verify your connection before processing real orders.
How KSeF Token Authentication Works
Unlike OAuth flows or persistent API keys, KSeF authentication works at the session level. A session is a bounded window during which you open a connection, submit invoice batches, and then close the session to receive a UPO. The token issued by the KSeF portal is used only to initiate sessions โ it is not sent with every individual API call.
Full Authentication Flow
Step 1: Request authorisation challenge
POST /api/online/Session/AuthorisationChallenge
โ Body: {
"contextIdentifier": {
"type": "onip",
"identifier": "YOUR_NIP"
}
}
โ Response: {
"challenge": "abc123...",
"timestamp": "2025-03-01T10:00:00Z"
}
Step 2: Sign the challenge (HMAC-SHA256 using your token as key)
Signed = HMAC_SHA256(key=TOKEN, data=CHALLENGE+TIMESTAMP)
Step 3: Exchange signed challenge for session token
POST /api/online/Session/AuthorisationToken
โ Body: {
"challenge": "abc123...",
"authorisation": "SIGNED_VALUE",
"identifier": { "type": "onip", "identifier": "YOUR_NIP" }
}
โ Response: {
"sessionToken": {
"token": "SESSION_TOKEN_STRING",
"context": { "credentials": [...] }
}
}
Step 4: Use SESSION_TOKEN as Bearer header for all subsequent calls
Authorization: Bearer SESSION_TOKEN_STRING
KSeF Pro handles all four steps automatically. The module manages session tokens internally, refreshes them when they expire, and never exposes raw session tokens in the PrestaShop admin interface or logs.
Why Sessions Expire
KSeF sessions expire after 30 minutes of inactivity on the MF servers. This is a government-imposed security limit and cannot be changed. KSeF Pro tracks session age and opens a new session automatically if the previous one has expired before a submission attempt.
For stores that submit invoices infrequently (one or two per day), the module opens a fresh session for each batch. For high-volume stores, multiple invoices are batched into a single session to reduce API overhead.
Test vs. Production Environments
Test Environment (ksef-test.mf.gov.pl)
| Characteristic | Test | Production |
|---|---|---|
| URL | https://ksef-test.mf.gov.pl/api | https://ksef.mf.gov.pl/api |
| FA(2) XML format | Same as production | Authoritative |
| Session tokens | Real (from test portal) | Real (from production portal) |
| UPOs issued | Yes โ functionally identical | Yes โ legally binding |
| KSeF-IDs assigned | Yes โ distinct prefix | Yes โ permanent record |
| Appears in VAT ledger | No | Yes โ permanent |
| Legal standing | None | Mandatory |
Always configure KSeF Pro against the test environment first. The test environment is a full-fidelity replica โ it accepts the same FA(2) XML, issues real session tokens and UPOs, and validates your NIP and signing pipeline identically to production. The only differences are that test submissions do not appear in your official KSeF ledger and cannot be used as VAT evidence.
Switching Environments
Environment selection is in KSeF Pro โ Configuration โ KSeF Connection tab โ Environment. Switching environments does not erase your token โ but test and production tokens are different and cannot be used interchangeably. You need separate tokens for each environment.
After switching to production, re-enter your production token, click "Verify Token", and confirm the green indicator before processing any orders.
NIP Registration in Production KSeF
Before your first production submission, verify your NIP is registered and active in KSeF:
- Go to
https://ksef.mf.gov.pl - Click Sprawdลบ status NIP (Check NIP status)
- Enter your NIP and confirm it shows as active
If your NIP is not registered, contact your accountant or the Polish tax authority (Urzฤ d Skarbowy). Registration is typically automatic for all active VAT payers in Poland, but new companies or recently re-registered entities may have a delay.
NIP Validation
KSeF Pro performs NIP validation at two points:
1. On Configuration Save
When you save the Seller Data tab, KSeF Pro:
- Strips all formatting characters (dashes, spaces,
PLprefix) - Validates the 10-digit format
- Applies the checksum algorithm:
- Multiply each of the first 9 digits by weights: 6, 5, 7, 2, 3, 4, 5, 6, 7
- Sum the products
- Check digit (position 10) must equal
sum mod 11
- If validation passes and network checks are enabled, cross-references via the GUS Regon API
A red inline warning appears if the checksum fails โ this almost always means a transcription error (digit transposition or copy-paste with a space included).
2. Before Every Submission
Immediately before opening a KSeF session, KSeF Pro sends a verification call to the configured environment to confirm the token/NIP pair is still valid. If the token has been revoked or the NIP deactivated in KSeF:
- The submission is blocked
- An error entry is written to the audit log
- No order status changes occur
- The error is logged with the KSeF API error code for diagnosis
This pre-flight check prevents situations where sessions open but all submitted invoices are rejected due to an account issue.
Session Token Lifecycle
| State | Description | Admin Panel Indicator | |---|---|---| | No session | Module is idle; no connection to KSeF | Grey | | Authorising | Challenge/response exchange in progress | Blue spinner | | Active | Session open; invoices can be submitted | Green | | Sending | Batch submission in progress | Blue with progress | | Closing | Session close requested; awaiting UPO | Yellow | | Closed | UPO received and archived | Green check | | Terminated | Session abandoned without UPO | Red โ invoices NOT accepted | | Expired | Session timed out before close | Orange โ re-submit required |
The Terminated state is the critical one: any invoices submitted in a terminated session were not accepted by KSeF and do not have KSeF-IDs. They must be re-submitted in a new session. KSeF Pro marks these as TERMINATED in the audit log and does not auto-retry them โ you must manually re-trigger submission from the audit log after resolving the underlying error.
Session Management Panel
Access the live session status at KSeF Pro โ Session Management.

From this panel you can:
- View the current session state and reference number
- Manually close an open session (triggers UPO download)
- Terminate an open session if you need to abort a batch
- View the session history with open/close timestamps and invoice counts
Manual Session Control
In most cases, KSeF Pro manages sessions automatically. Manual control is needed when:
- A session is stuck in
SENDINGstate (network interruption mid-batch) - You want to close a session immediately rather than waiting for the automatic close timeout
- You need to terminate a session to discard a batch with an XML error before any invoices are accepted
Terminate with caution: Terminating a session discards all submitted invoices. They must be re-submitted. If any invoices in the batch were already accepted by KSeF before termination, they retain their KSeF-IDs โ termination only discards pending items in the session queue.
Connectivity Troubleshooting
Firewall Requirements
KSeF Pro makes outbound HTTPS requests from your web server. Add these hostnames to your outbound allowlist:
| Endpoint | Port | Protocol |
|---|---|---|
| ksef-test.mf.gov.pl | 443 | HTTPS |
| ksef.mf.gov.pl | 443 | HTTPS |
Use hostname-based rules, not IP-based rules. The Ministry of Finance manages the IP addresses behind these hostnames and may change them without notice.
Testing Connectivity
From your server's command line:
# Test connectivity to test environment
curl -I https://ksef-test.mf.gov.pl/api/online/Session/AuthorisationChallenge \
-H "Content-Type: application/json"
# Expected: HTTP/2 405 (Method Not Allowed โ confirms host is reachable)
# Test connectivity to production
curl -I https://ksef.mf.gov.pl/api/online/Session/AuthorisationChallenge \
-H "Content-Type: application/json"A 405 Method Not Allowed response confirms:
- The host is reachable
- TLS certificate is valid
- Outbound port 443 is open
Any other result (timeout, Connection refused, SSL error) indicates a server-side network restriction. Contact your hosting provider with these test results.
TLS Certificate Validation
KSeF uses certificates issued by the Polish national CA infrastructure. On some older server configurations, the CA chain is not in the system trust store.
Verify:
curl -v https://ksef.mf.gov.pl 2>&1 | grep -E "SSL|certificate|verify"If you see SSL certificate problem: unable to get local issuer certificate, update your CA bundle:
# Debian/Ubuntu
apt-get update && apt-get install ca-certificates
# CentOS/RHEL
yum update ca-certificatesToken Rotation
KSeF tokens can be time-limited or permanent. The Ministry of Finance recommends rotating tokens periodically for security. When you rotate your token:
- Generate the new token on the KSeF portal with the same NIP and scopes.
- In KSeF Pro โ KSeF Connection, replace the old token with the new one.
- Click "Verify Token" to confirm the new token works.
- Do not delete the old token on the KSeF portal until you have confirmed the new one works โ simultaneous tokens are allowed.
Token rotation does not affect existing audit records or KSeF-IDs. All historical data remains associated with the NIP, not the token.