Authentication
Titancore authenticates API requests with signed JWT bearer tokens through PyJWT. The guard verifies passwords through the hashing module. Applications own account persistence and decide which accounts remain eligible.
Implement Authenticatable and UserProvider from
titancore.contracts.auth. Account objects expose
get_auth_identifier() -> str and get_auth_password() -> str.
The password method returns the stored encoded hash.
The provider implements two asynchronous methods.
retrieve_by_id(identifier)returns an eligible account orNone.retrieve_by_credentials(credentials)looks up an eligible account using application login fields and returns the account orNone.
The guard removes the plain password before calling the credentials lookup.
Applications can use SQLAlchemy queries in their provider. Disabled and
deleted accounts should return None. The guard reloads eligibility for every
bearer authentication.
Register your provider instance and the framework service providers after configuration bootstrap.
from typing import cast
from titancore.config import Repository
from titancore.contracts.auth import UserProvider
from titancore.auth import AuthServiceProvider
from titancore.facades import Env
from titancore.hashing import HashingServiceProvider
config = cast(Repository, app["config"])
config.set("auth.jwt.secret", Env.get("JWT_SECRET"))
app.instance(UserProvider, users)
app.register(HashingServiceProvider())
app.register(AuthServiceProvider())
Here app is the bootstrapped application and users is your account
provider. Read the signing key from the process environment or a secret
manager. HS256 requires at least 32 bytes of secret key material.
Save public JWT settings in config/auth.yaml.
jwt:
algorithm: HS256
issuer: titancore
audience: api
ttl: 3600
The TTL is measured in seconds. Supported algorithms are HS256, RS256, and
ES256. For asymmetric algorithms, secret contains the private signing PEM
and public_key contains the public verification PEM. The decoder pins the
configured algorithm and requires subject, issuer, audience, issued time,
not-before time, expiration, and token identifier claims.
Issue tokens from your own login route.
from titancore.auth.exceptions import AuthenticationError
from titancore.facades import Auth, Route
async def login(credentials: dict[str, object]) -> dict[str, str]:
token = await Auth.attempt(credentials)
if token is None:
raise AuthenticationError
return {"access_token": token, "token_type": "Bearer"}
Route.post("/login", login)
attempt returns a token or None. Auth.login(user) issues a token for an
account the caller has already authenticated. Token issuance does not select
a current request user.
Protect a route or group with Authenticate().
from titancore.auth import Authenticate
from titancore.facades import Auth, Route
async def profile() -> dict[str, str | None]:
return {"id": await Auth.id()}
Route.get("/profile", profile).middleware(Authenticate())
Clients send Authorization: Bearer <token>. The middleware sets
request.state.user and scopes Auth.user(), Auth.id(), and
Auth.check() to the handler. Missing or invalid credentials receive HTTP
401 with a bearer challenge. The context is restored when the handler
completes or raises.
Auth.authenticate(token) verifies a token and retrieves its account without
selecting request identity. Background operations can use
with guard.using(user) after resolving await Auth.guard().
Access tokens remain valid until expiration while their account remains eligible. Refresh tokens and token revocation storage are future work. Applications own login rate limiting and account recovery.
Built-in database accounts¶
Applications using the framework ORM can extend titancore.auth.User and
declare their own columns. The base supplies get_auth_identifier() and
get_auth_password(). Override auth_identifier_name and
auth_password_name when columns differ from id and password.
In config/auth.yaml, declare data and environment references:
jwt:
secret: !env [APP_KEY, ""]
providers:
users:
credentials: [email]
conditions:
active: true
After configuration bootstrap, register the model in application wiring:
from app.models.user import User
application["config"].set("auth.providers.users.model", User)
Register AuthServiceProvider(users=DatabaseUserProvider) alongside the existing
database and hashing providers. Import both auth classes from titancore.auth.
The provider applies trusted conditions to both identifier and credential
queries, converts JWT subjects through the ORM identifier type, excludes
password fields, and rejects unconfigured credential fields.
AuthServiceProvider also registers the gate. Put application ability callbacks
in auth.abilities, or define policies using the Gate facade during the
application lifecycle. Custom UserProvider implementations remain supported.
The separate AuthorizationServiceProvider has been removed; remove its imports
and registrations when updating existing applications.