A production-ready GNAP (Grant Negotiation and Authorization Protocol) authentication server implementation, part of the eduID IAM suite.
SUNET Auth Server is an authentication server that implements the GNAP protocol (RFC 9635), allowing users to request JWT access tokens using various authentication methods including mutual TLS, JWKs, and SAML2. It supports both dynamic and static client configuration.
- GNAP Protocol: Full implementation targeting RFC 9635
- Multiple Authentication Methods:
- Mutual TLS (mTLS) with certificate validation
- JWK-based authentication (JWS, detached JWS and HTTP Message Signatures
httpsig) - SAML2 Service Provider integration
- Certificate Authority (CA) trust validation
- Trust Frameworks:
- TLS-FED (TLS Federation) metadata support
- SAML metadata trust (MDQ - Metadata Query Protocol)
- Custom CA certificate chains
- User Interaction: Redirect and user code start modes, with an explicit resource owner consent step bound to the browser that started the interaction
- Flexible Configuration: Support for both static and dynamic client registration
- Production-Ready: Built with FastAPI, includes health checks, comprehensive logging, and Docker support
- Python 3.11+
- MongoDB (for transaction state storage)
- Docker (optional, for containerized deployment)
-
Clone the repository:
git clone https://github.com/SUNET/sunet-auth-server.git cd sunet-auth-server -
Install dependencies using uv:
uv pip sync requirements.txt
Or using pip:
pip install -r requirements.txt
-
Configure the server: Create a configuration file (YAML or environment variables). See Configuration section.
-
Run the server:
uvicorn auth_server.run:app --host 0.0.0.0 --port 8080
# Build the image
docker build -t sunet-auth-server .
# Run the container
docker run -p 8080:8080 \
-e app_name=auth-server \
-e app_entrypoint=auth_server.run:app \
-e AUTH_TOKEN_ISSUER=https://your-domain.com \
-e MONGO_URI=mongodb://mongo:27017/auth_server \
sunet-auth-serverThe server is configured using environment variables or a YAML configuration file. Key configuration options include:
| Variable | Description | Default |
|---|---|---|
AUTH_TOKEN_ISSUER |
JWT token issuer identifier (required) | - |
AUTH_TOKEN_AUDIENCE |
JWT token audience | None |
AUTH_TOKEN_EXPIRES_IN |
Token expiration time | 10 hours |
MONGO_URI |
MongoDB connection string | None |
KEYSTORE_PATH |
Path to JWKS keystore file | keystore.jwks |
SIGNING_KEY_ID |
Key ID for signing tokens | default |
Enable specific authentication flows using the AUTH_FLOWS configuration:
auth_flows:
- ConfigFlow # Static client configuration
- CAFlow # Certificate Authority validation
- MDQFlow # SAML metadata query
- TLSFEDFlow # TLS Federation metadata
- InteractionFlow # User interaction (SAML2 SP)
- TestFlow # Testing purposes onlyFor SAML2 Service Provider functionality:
pysaml2_config_path: /path/to/saml2_config.py
saml2_discovery_service_url: https://ds.example.com
saml2_single_idp: https://idp.example.com/metadata # Optional: skip discoveryConfigure TLS Federation metadata sources:
tls_fed_metadata:
- remote: https://metadata.tls-fed.org/federation.json
jwks: /path/to/trust/jwks.json
strict: true
- local: /path/to/local/metadata.json
jwks: /path/to/trust/jwks.jsonConfigure pre-registered clients:
client_keys:
client-id-1:
proof:
method: mtls
cert: "-----BEGIN CERTIFICATE-----\n..."
claims:
scope: "example.org"
custom_claim: "value"httpsig (RFC 9635 7.3.1, RFC 9421 and RFC 9530) is supported for keys sent by value (public JWK) and for keys
in client_keys. The proof is given either as a string or as an object:
"proof": "httpsig"
"proof": {"method": "httpsig", "alg": "ecdsa-p256-sha256", "content-digest-alg": "sha-512"}- String form: the algorithm comes from the
alg(a JWS name) of the JWK, which is then required. Supported:ES256(ecdsa-p256-sha256),ES384(ecdsa-p384-sha384),RS256(rsa-v1_5-sha256),PS512(rsa-pss-sha512) andEdDSA(ed25519, anOKPJWK withcrvEd25519). The Content-Digest algorithm issha-256. - Object form:
algis required and must match the key (and the JWKalgif there is one).content-digest-algissha-256(default) orsha-512. - The JWK needs a
kid, it must be thekeyidof the signature. Private keys (detc.) sent by value are rejected. HMAC (octkeys) is not supported. The algorithm is never taken from the message, an explicitalgsignature parameter is rejected. - Signature parameters:
tagmust begnap,createdis required and must be at mostproof_httpsig_max_ageold (and not more thanproof_httpsig_clock_skewin the future),expiresmust not have passed. A signednonceis required by default and can only be used once per key. - Covered components:
@methodand@target-urialways,content-digestwhen the request has a body andauthorizationfor requests carrying an access token (continuation and token management requests). - Several signatures can be sent. The request is accepted if one of them is valid.
- Requests to
/continueand/tokenmust be signed with the key of the grant request.
Nonces are stored in MongoDB (proof_nonces, expiring). Without mongo_uri they are only remembered by the
running process, which does not protect a deployment with several workers or instances.
| Variable | Description | Default |
|---|---|---|
PROOF_HTTPSIG_MAX_AGE |
How old a signature's created may be |
5 minutes |
PROOF_HTTPSIG_CLOCK_SKEW |
Accepted clock difference between client and server | 30 seconds |
PROOF_HTTPSIG_REQUIRE_CONTENT_TYPE |
Require content-type to be signed when there is a body |
false |
PROOF_HTTPSIG_NONCE_REQUIRED |
Require a signed nonce. Disabling it leaves requests replayable until proof_httpsig_max_age expires |
true |
PROOF_EXTERNAL_BASE_URL |
Scheme and authority clients sign, see below | None |
@target-uri (httpsig) and uri (jws and jwsd) must match the URL the client used. A proxy that terminates TLS or
rewrites host or port makes the server see another URL than the client signed. Either set
proof_external_base_url to the public base URL (scheme, host and port only, no credentials, path, query or
fragment, for example https://auth.example.com), which is the recommended option, or run uvicorn/gunicorn with proxy
headers support (--proxy-headers --forwarded-allow-ips=<proxy address>) so the scheme and host are restored.
Forwarded headers are never read by the auth server itself. The path and query must be the same after the proxy as
they were for the client.
If you use --forwarded-allow-ips, list only the proxy address. Any address in that list can set the scheme and host
the server reconstructs, so a broad list (such as * or client-routable space) lets a client sign a forged authority
and the URI binding loses its meaning.
POST /transaction
Initiate a GNAP transaction to request access tokens.
curl -X POST https://auth.example.com/transaction \
-H "Content-Type: application/json" \
-d '{
"access_token": [{
"flags": ["bearer"],
"access": [{"type": "example-api", "scope": "example.org"}]
}],
"client": {
"key": {
"proof": "mtls",
"cert#S256": "HTOXGzzHrtiq_Art..."
}
}
}'curl -X POST https://auth.example.com/transaction \
-H "Content-Type: application/json" \
-d '{
"access_token": [{
"flags": ["bearer"],
"access": [{"type": "example-api", "scope": "example.org"}]
}],
"client": {
"key": "configured_key_name"
}
}'curl -X POST https://auth.example.com/transaction \
-H "Content-Type: application/json" \
-d '{
"access_token": [{
"flags": ["bearer"],
"access": [{"type": "example-api", "scope": "example.org"}]
}],
"client": {
"key": {
"proof": "mtls",
"cert#S256": "HTOXGzzHrtiq_Art..."
}
},
"interact": {
"start": ["user_code_uri"]
}
}'POST /continue/{continue_reference}
Continue an in-progress GNAP transaction.
GET /interaction/redirect/{transaction_id}
Start the interaction. The first browser to arrive is bound to the transaction: the server stores an
interaction session id and a CSRF token and sets an httponly per-transaction session cookie. Later
requests from any other browser are rejected with 403.
If the user is not authenticated yet, this redirects to the SAML2 SP (/saml2/sp/authn/{transaction_id}).
Once authentication is done, the same URL renders the consent screen listing the requested access and the
subject information the client asked for.
POST /interaction/consent/{transaction_id}
Submit the resource owner's decision from the consent screen. Form fields: decision (approve, anything
else counts as a denial) and csrf_token. Requires the interaction session cookie set by the redirect
endpoint. Approval sets the transaction to approved, denial sets it to denied; either way the agreed
finish method (redirect or push) is triggered.
Continuing a denied transaction fails with 403 and the GNAP error code user_denied.
GET / POST /interaction/code
Show and submit the user code for the user_code / user_code_uri interaction start modes. A valid code
redirects to /interaction/redirect/{transaction_id}.
GET /status/healthy
Returns server health status.
curl http://localhost:8080/status/healthyPre-configured clients with static credentials and claims.
- Loads client keys and claims from configuration
Validates client certificates against a trusted CA bundle.
- Loads CA certificates from
ca_certs_path - Validates certificate chain and validity period
- Extracts organization ID from certificate (optional)
- Supports revocation checking
Retrieves and validates certificates from SAML metadata.
- Queries MDQ server for entity metadata
- Validates certificates from SAML metadata
Uses TLS-FED metadata for certificate validation.
- Loads and validates TLS-FED metadata
- Supports both remote and local metadata sources
- Validates entity issuer certificate from metadata
- Caches metadata with configurable TTL
Integrates SAML2 SP for user authentication flows.
- Redirects user to SAML IdP
- Processes SAML assertions
- Asks the resource owner to approve or deny the request on a consent screen before the transaction is approved — authentication alone is not approval
- Binds the interaction to the browser that started it, so an interaction URL handed to someone else can not be used to approve the transaction
- Issues access tokens based on authentication
- Supports discovery service for IdP selection
The consent screen does not name the client: InteractionFlow clients are anonymous and client.display is
self-asserted (RFC 9635 2.3), so showing it would be misleading.
For development and testing purposes only. Do not use in production — it issues access tokens to anyone who asks, with no key proof at all.
Enable it in the configuration:
auth_flows:
- TestFlowOr as an environment variable (the value is a JSON list):
AUTH_FLOWS='["TestFlow"]'Then send a grant request with the test proof method and no key material:
curl -X POST http://localhost:8080/transaction \
-H "Content-Type: application/json" \
-d '{
"access_token": [{
"flags": ["bearer"],
"access": [{"type": "example-api", "scope": "example.org"}]
}],
"client": {
"key": {
"proof": "test"
}
}
}'The response contains a signed access token right away, with auth_source: test and source: test mode in
the claims. The bearer flag is still required — see Known Limitations.
TestFlow also accepts the real proof methods (mtls, jws, jwsd): if proof is anything but test, the
proof is verified as usual, only the client key is not looked up in any trust source. This is how the test
suite exercises proof verification without an MDQ server or a CA bundle.
Flows are tried in the order they are configured, and TestFlow never rejects a request whose proof verifies
against the key in the request itself, so a configured TestFlow short circuits every flow after it. Leave it
out of any deployment that serves real clients.
# Install development dependencies
uv pip sync dev_requirements.txt
# Run tests
make test
# Type checking
make typecheck
# Code formatting
make reformatThe project uses:
- ruff for linting and formatting
- mypy for static type checking
- pytest for testing
pytest --log-cli-level DEBUGThe scripts/ directory contains helpful utilities:
gen_jwks.py: Generate JWKS keystoregen_cert.py: Generate test certificatestoken_info.py: Decode and inspect JWT tokensinspect_tls_fed_metadata.py: Inspect TLS-FED metadatapem2fingerprint_rfc8705.py: Get cert#S256 value from pem certvalidate_tls_fed_metadata.py: Validate TLS-FED metadata signatures
src/auth_server/
├── api.py # FastAPI application setup
├── flows.py # Authentication flow implementations
├── config.py # Configuration management
├── models/ # Pydantic models for GNAP, JOSE, etc.
│ ├── gnap.py # GNAP protocol models
│ ├── jose.py # JWK, JWS models
│ └── claims.py # JWT claims models
├── routers/ # FastAPI route handlers
│ ├── root.py # Grant request endpoints
│ ├── interaction.py # User interaction and consent endpoints
│ ├── saml2_sp.py # SAML2 SP endpoints
│ ├── status.py # Health check endpoints
│ └── templates/ # Consent, user code and result pages (Jinja2)
├── proof/ # Proof verification (mTLS, JWS, etc.)
├── db/ # Database models and operations
└── tests/ # Test suite
The following GNAP features are not yet implemented:
- HTTPSIG key rotation (
gnap-rotatesignatures) and HMAC algorithms (asymmetric keys only) - Key-bound access tokens — grant requests must include the
beareraccess token flag; requests without it are rejected withinvalid_request - Multiple access token requests (array of token requests in a single grant)
- Client/user by reference
- Access token rotation (
POST /token/{ref}returnsinvalid_rotation) - Access token introspection (RFC 9767)
- App interaction start mode
- Subject
sub_ids
Note: revoking an access token (DELETE /token/{ref}) removes AS-side state only — the JWT remains valid to offline validators until it expires.
These features may be added in future releases based on demand and use cases.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Run
make reformatandmake typecheck - Submit a pull request
This project is licensed under the BSD 2-Clause License. See LICENSE file for details.
- Documentation: https://github.com/sunet/sunet-auth-server
- API Documentation: https://auth.sunet.se/docs
- Issues: GitHub Issues
Developed and maintained by SUNET (Swedish University Computer Network) as part of the eduID identity and access management infrastructure.