H· Hawiyati Documentation

Core Concepts

This guide explains how Hawiyati works from the inside out — how users are authenticated, how sessions are established and maintained, how service providers receive identity assertions, and how policies and risk signals combine to make dynamic access decisions. Read these concepts before integrating applications or configuring production policies.

This guide explains how Hawiyati works from the inside out — how users are authenticated, how sessions are established and maintained, how service providers receive identity assertions, and how policies and risk signals combine to make dynamic access decisions. Read these concepts before integrating applications or configuring production policies.

🔐
Authentication
How Hawiyati verifies who a user is — password, TOTP, FIDO2, and OTP methods, sequenced by policy.
📱
Multi-Factor Authentication
Each second-factor type, how it works internally, replay protection, and admin enrollment flows.
🔗
Sessions & Authorization
Two-layer session model, SSO fast path, SAML assertion structure, OIDC tokens, and Single Logout.
🌐
Application Federation
SAML 2.0 and OIDC integration patterns, attribute release, and how Hawiyati integrates with applications.
📋
Authentication Policies
Ordered rule sets evaluated per SP — who, where, when, and what action to take.
⚡
Adaptive Risk Engine
Contextual signals, scoring pipeline, enforcement modes, and tuning for real-world traffic.

Platform Architecture Overview

Hawiyati is composed of specialised microservices communicating over HTTPS and gRPC. The four zones below show where each service lives, what it handles, and how requests flow from external actors through the entry layer into the platform and data layers. Understanding this structure helps with integration, troubleshooting, and capacity planning.

Teal Innovation architecture preview showing external actors, entry and federation, platform services and shared runtime, and data and infrastructure.
Teal Innovation — visual design preview. Draft based on the supplied component diagram; relationships are illustrative and have not been verified against the code. Open full-size diagram.
Hawiyati IAM Platform — Component Architecture HAWIYATI IAM PLATFORM — COMPONENT ARCHITECTURE Spring Boot 3.5 · Java 25 · gRPC EXTERNAL ACTORS ENTRY LAYER & FEDERATION HTTPS · SAML 2.0 · OIDC · WebAuthn PLATFORM SERVICES HTTPS internal · gRPC DATA & INFRASTRUCTURE JDBC · Redis pub/sub · gRPC User Browser Browser · Mobile App Administrator Admin Console SAML Service Provider SAML 2.0 OIDC Relying Party OIDC · OAuth 2.0 SCIM Client HR System · Directory hawiyati-gateway Spring Cloud Gateway · :8080 Routing · TLS termination hawiyati-http-server IdP Login · MFA · FIDO2 · :8085 SAML ACS · OIDC callback · Account BFF hawiyati-federation SAML 2.0 · OIDC · :8087 Assertion & token issuance · Policy hawiyati-admin Admin Console · :8095 · WebFlux hawiyati-account Account Portal · :8096 · BFF/OIDC hawiyati-scim SCIM 2.0 API · :8098 hawiyati-session · :9004 hawiyati-cache · :9003 hawiyati-infra · :9002 PostgreSQL hawiyati · hawiyati_identity Redis / Valkey Sessions · Cache · Rate limits Audit & Logs CEF Syslog · OTel · SIEM PKI & Keystore SAML · OIDC · mkcert TLS External Actor External System Entry / Federation Platform Service gRPC Service Data Store

The sections below explain how each zone behaves at runtime. For module ports, gRPC service definitions, and deployment topology, see the Implementation Guide.


How Authentication Works

Authentication in Hawiyati is the process of verifying a user's identity before granting access to a service provider. It runs through a sequenced pipeline: the IdP collects evidence via one or more methods, evaluates it against the user's stored credentials, and upon success issues a session and a federation artifact (SAML assertion or OIDC token set).

Hawiyati is the Identity Provider (IdP). Every login begins when a browser follows a SAML SSO request or OIDC authorization redirect to hawiyati-http-server. From that entry point, the IdP constructs a sequence of authentication steps, drives the user through them, and — when all steps succeed — hands control back to hawiyati-federation to issue the assertion or tokens.

Authentication is stateful within the login flow. A LoginFlowState object is stored in the user's IdP browser session for the duration of the ceremony. It tracks:

FieldContents
providerSequenceOrdered list of authentication steps to execute
stepIndexCurrent position in the sequence
usernameDiscovered at or after the first step completes
amrListMethods successfully completed so far (included verbatim in OIDC amr)
loaReachedHighest authentication assurance level achieved so far
Per-provider scratch stateTemporary data such as the OTP HMAC or FIDO2 challenge, stored server-side for the step duration

The flow is complete when stepIndex passes the end of the sequence. The IdP then establishes a session and hands control to the federation layer.


Supported Authentication Methods

Hawiyati supports five authentication methods, each mapped to a named provider in the login engine.

MethodProvider codeFactor categoryAALPhishing-resistantHardware-bound
Password pwd Knowledge AAL1 No No
TOTP (authenticator app) totp Possession AAL2 No No
Email OTP email_otp Possession AAL2 No No
SMS OTP sms_otp Possession AAL2 No No
FIDO2 / WebAuthn passkey fido2 Possession + Inherence AAL2 Yes Yes

Factor categories

Knowledge — something the user knows (password). Possession — something the user has (phone, authenticator app, security key). Inherence — something the user is or does (biometric confirmed locally by the device for passkeys). FIDO2 uniquely covers both possession and inherence.


The Login Flow

Every login follows the same pipeline: receive the SSO request, evaluate policy, construct the step sequence, execute each step, then issue the assertion or tokens. The steps below describe the happy path for a policy-driven MFA login.

User Browser
hawiyati-federation
Policy + Risk
hawiyati-http-server
DB / Redis
1
User Browser→hawiyati-federation
SP redirects user with SAML AuthnRequest or OIDC /authorize. Federation stores the SSO request in IdP browser session.
2
hawiyati-federation→Policy + Risk
Evaluate SP's authentication policy (group, network zone, time window) in parallel with adaptive risk engine → result: ALLOW / MFA_REQUIRED / DENY and required auth methods
3
hawiyati-federation↔Redis
Check IdP browser session for idp.authenticatedUser. If found and policy allows SSO reuse → skip to step 6 (fast path).
4
hawiyati-http-server→User Browser
Render login form (primary factor: password). On submission — Argon2id verification (local) or LDAP bind (directory accounts). Writes amr=[pwd], loaReached=AAL1.
5
hawiyati-http-server→User Browser
Render second factor if policy requires MFA (TOTP / email OTP / SMS OTP / FIDO2). Successful completion raises loaReached to AAL2, appends to amr.
6
hawiyati-federation→User Browser
Issue signed SAML assertion (POST to ACS) or OIDC authorization code (redirect). IdP browser session now carries idp.authenticatedUser for SSO reuse.
1
SP initiates SSO
Browser follows a SAML AuthnRequest or OIDC /authorize redirect to hawiyati-federation. The SSO request is stored in the IdP browser session.
2
Policy evaluation
hawiyati-federation evaluates the SP's authentication policy (group, network zone, time window) and determines the required authentication action: ALLOW, MFA_REQUIRED, or DENY.
3
SSO fast path check
If the user already has a valid IdP browser session (idp.authenticatedUser is set), the flow skips login and jumps directly to step 6. Otherwise, the browser is redirected to the login form.
4
Primary factor — password
hawiyati-http-server renders the password form. On submission: Argon2id verification (local accounts) or LDAP bind (directory-sourced accounts). Successful completion writes amr=[pwd], loaReached=AAL1 to flow state.
5
Second factor (if required by policy)
The IdP renders the next step in the sequence — TOTP code entry, email/SMS OTP, or FIDO2 assertion prompt. Successful completion appends to amr and raises loaReached to AAL2.
6
Assertion issuance
Flow complete. hawiyati-federation issues a signed SAML assertion or OIDC authorization code. The IdP browser session now carries idp.authenticatedUser for SSO re-use.
ℹ
Account status is checked at the password step

A user with status Pending Approval or Suspended is blocked after the password step. The error message does not indicate whether the password was correct — this prevents account status enumeration.


Flow Sequence Construction

The set of authentication steps is determined before the first form is rendered. Two sources drive the sequence.

Source 1 — SP accepted methods (no policy)

When a service provider has no authentication policy, the IdP uses the SP's accepted methods list from its registration record.

SP accepted methodsBehavior
List includes pwdPassword form shown first; other methods available as "sign in another way" links
Exactly one non-password methodBrowser taken directly to that method's form
Multiple non-password methods, no passwordA method picker screen is shown first

In this mode, the user can switch between offered methods. A user who selects a method they are not enrolled in will fail at that method's own verification step — the IdP does not pre-filter the picker.

Source 2 — authentication policy

When the SP has an authentication policy, the policy result drives the sequence directly.

Policy resultSequence
ALLOWPassword only (pwd)
MFA_REQUIRED with specific factorsPassword, then each required factor in order (e.g. pwd → totp)
MFA_REQUIRED with no specific factorsPassword, then a method picker offering all enrolled MFA methods
DENYA denial screen — no credentials accepted
⚠
Policy-driven flows are fixed

Policy-driven flows do not allow users to switch to alternative methods outside the mandated sequence. The order is fixed by the policy configuration.


Authentication Assurance Levels (AAL)

Hawiyati tracks the highest assurance level (AAL) reached during a login. The loaReached value is included in the session and used by the federation layer when building SAML AuthnContextClassRef or OIDC ACR values.

LevelNameHow to reach it
AAL1 Single factor Only a knowledge factor (password) was verified. Standard for non-sensitive applications.
AAL2 Multi-factor or phishing-resistant single factor Any second factor (TOTP, email OTP, SMS OTP) completed after password; OR FIDO2 completed alone as the sole required method.

A password-only login yields AAL1. Adding any MFA method raises the session to AAL2. A FIDO2-only login also achieves AAL2 and additionally satisfies phishing-resistance requirements for high-assurance applications.


Device Tracking

At the start of each authentication request, Hawiyati reads or issues a hwd_id cookie. This cookie is the basis for the NEW_DEVICE risk signal in the adaptive risk engine.

AttributeValue
Cookie namehwd_id
ValueRandom UUID (cryptographically random)
HttpOnlyYes — not readable by JavaScript
SecureYes — TLS only
SameSiteLax
Max-Age400 days

The cookie contains only a random identifier — no user data, no session state. A user who clears cookies or switches browsers will receive a new device ID, which may trigger a NEW_DEVICE risk signal on their next login from the new browser.


Lockout & Rate Limiting

ControlBehavior
OTP attempt limitsEmail OTP and SMS OTP allow a maximum of 5 attempts per issued code. After 5 failed attempts the step enters a locked state; the user must restart the login flow.
OTP expiryA code not used within 5 minutes (300 s) is invalidated. A new code must be requested via the resend button.
TOTP replay preventionEach 30-second window can be used at most once. An already-accepted window is permanently rejected even if the code digits are correct.
SMS rate limitingSMS delivery is rate-limited per phone number via a Redis sliding-window counter. The bucket key is SHA-256(phone) — the phone number itself is never stored in Redis. Limits are configurable per SMS gateway.
Password attempt trackingFailed password attempts are recorded and visible to admins at Admin → Login Attempts. Application-layer lockout is not enforced automatically; administrators can suspend accounts manually.

Multi-Factor Authentication

MFA requires users to prove identity using more than one factor type. Hawiyati supports four MFA methods in addition to the primary password factor. Each method has distinct security properties, enrollment requirements, and operational considerations. All MFA secrets and hashes are encrypted at rest.


TOTP — Authenticator App

TOTP (Time-based One-Time Password) generates 6-digit codes from a shared secret using RFC 6238. Compatible with any RFC 6238-compliant authenticator app: Google Authenticator, Microsoft Authenticator, Authy, 1Password, Bitwarden, and others.

ParameterValue
AlgorithmHMAC-SHA1 (RFC 6238 standard; compatible with all apps)
Code length6 digits
Time step30 seconds
Clock skew tolerance±1 step (±30 s) to accommodate slight device clock drift
Secret storageAES-256-GCM encrypted at rest; plaintext in memory only during enrollment and verification

Replay protection

Each successful TOTP verification records the 30-second time step that was consumed. A code from the same window cannot be reused — the step must be strictly newer than the last accepted step. This prevents an attacker who observes a valid code from using it within its validity window.

✓
Secret is shown exactly once

The TOTP shared secret is displayed as a QR code during enrollment. After enrollment completes, the plaintext secret is no longer accessible. Administrators cannot retrieve it. If the user loses their device, an admin must delete the credential and the user must re-enroll.


FIDO2 / WebAuthn Passkeys

FIDO2 is the strongest available authentication method. Verification uses the WebAuthn protocol — the server issues a challenge, the user activates their authenticator (hardware key or device biometric), and the authenticator signs the challenge. The signed assertion is verified using the stored public key. The private key never leaves the authenticator.

Why FIDO2 is uniquely strong

PropertyHow it works
Phishing-resistant Credentials are bound to the relying party origin (dev.hawiyati.org). A credential registered for this origin cannot be used by a phishing site at any other origin — the WebAuthn assertion includes the origin and the browser validates it cryptographically.
Hardware-bound On hardware security keys (YubiKey, SoloKey, etc.) the private key cannot be exported even if the device is physically seized. On platform authenticators (Face ID, Touch ID, Windows Hello) the key is protected by the device's secure enclave.
No shared secret The server stores public keys only. There is no server-side secret whose extraction would compromise all users.
Clone detection Each successful assertion increments a signature counter on the stored credential. If the received counter is not greater than the stored value, the assertion is rejected as a potential clone.

Supported authenticators

YubiKey / SoloKey (USB, NFC) Face ID / Touch ID (platform) Windows Hello (platform) Android biometric (platform) Hybrid flow (phone via Bluetooth)

Enrollment

FIDO2 credentials must be registered in the user's own browser via the WebAuthn API. Administrators cannot register a passkey on behalf of a user. Administrators can:

  • Send a FIDO2 enrollment invitation email via Admin → Users → [user] → Send Enrollment Invitation.
  • Delete all registered credentials for a user, forcing re-enrollment on their next login.
  • View the list of registered authenticators and their creation timestamps.

Email OTP

The email OTP step sends a 6-digit numeric code to the user's registered email address.

ParameterDefaultConfiguration key
Code length6 digitshawiyati.otp.code-length
Time to live300 s (5 min)hawiyati.otp.ttl-seconds
Maximum attempts5hawiyati.otp.max-attempts

How the code is protected

The plaintext code is emailed and immediately discarded. The server stores only an HMAC-SHA256 of the code (keyed with a server-side pepper). Verification compares HMACs in constant time, preventing timing side-channels. With a 5-attempt online cap, the 1,000,000 possible values search space is exhausted by rate limits before brute force is practical.

Anti-enumeration

The flow uses identical code paths and shows the same form whether or not the user has an email address registered. A user without a registered email receives no delivery and will fail — but the attacker cannot distinguish this from a wrong code by timing or UI differences.

Email masking

The form displays a masked version of the email address (f•••@example.com) to help the user identify which account received the code without exposing the full address.


SMS OTP

The SMS OTP step sends a 6-digit code to the user's registered phone number via a configurable HTTP SMS gateway. Code length, TTL, and attempt limits are identical to email OTP.

Rate limiting

SMS delivery is rate-limited per phone number using a Redis sliding-window counter. The bucket key is SHA-256(phone number) — the plaintext phone number is never stored in Redis. The window size and maximum request count are configurable per SMS gateway. If the rate limit is reached, the form shows an error and no new code is sent.

Phone masking

The form displays ***NNNN where NNNN is the last four digits of the registered phone number.

⚠
Gateway required

An SMS gateway must be configured in Admin → Settings → SMS Gateway before this method is functional. Without a gateway, SMS delivery is silently skipped — the user will never receive a code.


Recovery Codes

Recovery codes are emergency one-time credentials that allow a user to authenticate when their primary MFA device is unavailable. Each user can generate a set of recovery codes from their account portal.

PropertyDetail
DisplayShown exactly once at generation. The user must save them securely — they cannot be retrieved afterward.
StorageOnly an Argon2id hash of each code is stored. The plaintext is never persisted.
Single-useEach code is consumed on use. Used codes are marked as depleted and cannot be reused.
RegenerationThe user (or an admin on their behalf) can regenerate the entire set, which invalidates all previously issued codes.
!
Recovery codes are never logged

Recovery codes are excluded from all audit events, debug output, and log files. The raw code value is present only in memory during generation (to display to the user) and during verification (to hash for comparison).


MFA Enrollment & Admin Invitation Flow

Users enroll MFA methods through the account portal. Administrators can trigger enrollment for individual users via an invitation email.

1
Admin sends enrollment invitation
Admin → Users → [user] → MFA → Send Enrollment Invitation. Hawiyati sends an email with a time-limited enrollment link (15-minute TTL).
2
User clicks the enrollment link
The link authenticates the user via a one-time token and navigates directly to the MFA enrollment screen in the account portal.
3
User completes enrollment ceremony
For TOTP: scan QR code, enter a valid code to confirm. For FIDO2: browser invokes WebAuthn API, user activates authenticator. For email/SMS OTP: verify delivery by entering the first code.
4
Credential stored & audit event emitted
The new credential is stored (encrypted secret for TOTP, public key for FIDO2, hash for codes). An mfa.enrollment.success audit event is written.

Two-Layer Session Model

Hawiyati maintains two distinct kinds of session, each with a different purpose and lifetime. Understanding both layers is essential for correctly designing SSO, SLO, and token validation in integrated applications.

LayerCookieNamespacePurposeTTL
IdP browser session IDP_SESSION hawiyati:idp:session Drives SSO re-use. Holds login flow state and per-SP session list for SLO. 30 min max-inactive
Application session HAWIYATI_SESSION session:<uuid> Carries user attributes for the duration of an application interaction. 1 hour absolute

IdP Browser Session

The IdP browser session is a Spring WebSession backed by Redis. Session data is JSON-serialized via Jackson.

Cookie attributes

AttributeValueReason
HttpOnlyYesInaccessible to JavaScript
SecureYesTLS-only transmission
SameSiteNoneRequired for cross-site SSO: when a browser follows a redirect from an SP (e.g. saml.spdemo.org) to the IdP (dev.hawiyati.org), the browser treats this as a cross-site navigation. SameSite=None ensures the IdP session cookie is sent so the SSO fast path can find the existing session. Lax or Strict would break cross-domain SSO.

Session attributes

Attribute keyTypeContents
idp.authenticatedUserStringUsername of the authenticated user. Presence of this key is the SSO fast-path trigger.
idp.flowString (JSON)Serialized LoginFlowState — in-progress authentication state. Written at login start; removed on completion.
idp.authnRequestXmlStringRaw SAML AuthnRequest XML, held while the browser is at the login form.
idp.relayStateStringSAML relay state from the originating SSO request.
idp.activeSamlSessionsListActiveSpSession records — one per SP the user has logged into; used for SLO fan-out.
idp.slo.*VariousTemporary SLO chain state during an in-progress logout fan-out.

Application Session

The application session is managed by hawiyati-session (gRPC) and uses a two-level cache for performance at scale.

Storage architecture

L1: Caffeine in-JVM cache — 50,000 entries, expireAfterWrite 60s. Fastest reads; serves most requests without a network call.
L2: Redis — key session:<uuid>, TTL 3600 s. Authoritative store shared across all nodes.

PathBehavior
ReadL1 checked first. On miss, Redis is queried and the result is written back to L1.
WriteSession created in Redis first, then written to L1 to warm the cache immediately.
DestroyRedis key deleted; session ID published on session:invalidate pub/sub. All nodes (including publisher) drop the L1 entry. A pub/sub message of * clears the entire L1.

gRPC operations

MethodDescription
CreateSessionCreates a new session; returns session ID and expiry timestamp
GetSessionRetrieves a session by ID; returns NOT_FOUND if missing or expired
ValidateSessionChecks whether a session ID exists and has not expired
DestroySessionDeletes the session and publishes the invalidation event

SSO Fast Path

When a SAML or OIDC SSO request arrives and the user already has a valid IdP browser session (idp.authenticatedUser is present), the IdP issues the assertion or authorization code directly — no login form is shown. This is standard web-SSO behaviour.

If the attribute is absent (no session or expired session), the SSO request is stored in the session and the browser is redirected to the login form. After successful authentication, the SSO flow resumes automatically.

ℹ
Fast path respects policy

Even on the fast path, the IdP re-evaluates the SP's authentication policy. If the existing session does not meet the policy's required assurance level, the user is prompted to complete additional factors (step-up authentication) before the assertion is issued.


SAML Assertions & OIDC Tokens

SAML assertion structure

Hawiyati issues a SAML 2.0 Response containing a single signed Assertion. Key elements:

ElementDetail
NameIDFormat: urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified; Value: the authenticated principal (username)
SubjectConfirmationMethod: bearer; InResponseTo: originating AuthnRequest ID; NotOnOrAfter: issue time + 1 hour
ConditionsNotBefore: issue time − 30 s; NotOnOrAfter: issue time + 1 hour; AudienceRestriction: SP entity ID
AuthnStatementSessionIndex: unique UUID; AuthnContextClassRef: PasswordProtectedTransport
SigningThe <saml:Assertion> element is signed (not the outer <samlp:Response>). RS256-equivalent via XML-DSig with the IdP's X.509 certificate embedded in <KeyInfo>.
⚠
Assertion-level signing only

SP deployments that validate only the outer <samlp:Response> signature will not accept Hawiyati assertions. Verify that your SP library validates the <saml:Assertion> signature specifically.

OIDC tokens

TokenAlgorithmTTLPurpose
ID tokenRS256 (JWT)1 hourIdentity claim for the client. Includes user profile claims based on requested scopes.
Access tokenRS256 (JWT, RFC 9068)1 hourBearer credential for resource APIs. Header typ: at+JWT.
Refresh tokenOpaque30 daysExchanged for a new access token at /oidc/token with grant_type=refresh_token.
Authorization codeOpaque60 sSingle-use code from /authorize response. Replay attempts return invalid_grant.

Standard ID token claims

ClaimDescription
issIdP entity ID (issuer)
subAuthenticated principal
audClient ID
exp / iatExpiry / issued-at (epoch seconds)
auth_timeWhen the user actually authenticated (distinct from token issue time)
nonceAnti-replay nonce from the authorization request
at_hashLeft 128 bits of SHA-256 of the access token, base64url-encoded (§3.3.2.11)
amrAuthentication method references list (e.g. ["pwd","totp"])

Single Logout (SLO)

SLO allows a logout from one SP (or the IdP itself) to propagate to all other SPs the user is currently signed into. Hawiyati tracks active SP sessions in idp.activeSamlSessions.

SP-initiated SAML SLO chain

1
SP sends LogoutRequest
The initiating SP posts a signed LogoutRequest (HTTP-Redirect binding) to the IdP's SLO endpoint.
2
IdP clears own state
The IdP removes idp.authenticatedUser from the browser session and builds a pending list of other SP sessions to notify.
3
Fan-out to other SPs
The SLO chain is sequential — the IdP sends a LogoutRequest to each SP's SLO URL via HTTP-Redirect, waits for a LogoutResponse, then advances to the next SP. Chain state is held in idp.slo.* session attributes.
4
Final LogoutResponse to initiating SP
After all other SPs respond (or time out), the IdP sends the final LogoutResponse back to the initiating SP.
ℹ
SLO is best-effort

If an SP's SLO endpoint is unreachable or returns an unexpected response, the chain advances to the next SP. The IdP session is invalidated regardless of SP response. SPs that have no SLO URL registered are skipped.

⚠
Session revocation does not invalidate issued tokens

Revoking an IdP browser session does not terminate any OIDC access tokens or refresh tokens that have already been issued. Tokens are self-contained JWTs with their own expiry. To revoke a token, use the token revocation endpoint.


Session Security Properties

The following properties are fixed and cannot be changed through configuration:

PropertyDetail
IDP_SESSION is HttpOnly + SecureCannot be read by JavaScript; transmitted over TLS only
SAML assertions are assertion-signedThe <saml:Assertion> element is signed, not the outer Response
OIDC tokens are RS256-signed JWTsPrivate key stays in hawiyati-infra; verification requires the public key from the JWKS endpoint
Authorization codes are single-use60-second TTL; replay returns invalid_grant
PKCE supported (S256 and plain)Prevents authorization code interception attacks for public clients and mobile apps
Session cookies contain only session IDAll user data is server-side only; no user data in browser-readable form

SAML vs OIDC: Choosing a Protocol

Hawiyati supports both SAML 2.0 and OpenID Connect for integrating applications. The choice depends on your application type, technology stack, and existing infrastructure.

SAML 2.0OpenID Connect
Best forEnterprise apps, ERP, legacy SaaS with SAML built-inWeb apps, mobile apps, APIs, modern SaaS
Config exchangeXML metadata files (IdP ↔ SP)Discovery document at /.well-known/openid-configuration
Identity artifactSigned XML AssertionSigned JWT (ID token)
FlowBrowser POST/redirect bindingAuthorization Code (+ PKCE for public clients)
LogoutSLO chain via HTTP-Redirect (sequential)RP-initiated logout; front-channel or back-channel
Token formatXML assertion embedded in responseCompact JWT; access token (RFC 9068); refresh token
API accessNot designed for APIsAccess token as Bearer credential for resource APIs

SAML 2.0 Integration

Service providers integrate with Hawiyati as a SAML 2.0 Identity Provider. The integration requires exchanging metadata and registering the SP in the Hawiyati SP registry.

What the SP needs from Hawiyati

ArtifactWhere to get it
IdP Metadata XMLhttps://<idp-host>/saml/metadata
Entity IDIn the metadata: <EntityDescriptor entityID="...">
SSO endpoint (HTTP-POST)In the metadata: <SingleSignOnService Binding="urn:...HTTP-POST">
Signing certificateIn the metadata: <KeyDescriptor use="signing">
SLO endpointIn the metadata: <SingleLogoutService> (if SLO is enabled)

Supported features

SP-initiated SSO IdP-initiated SSO Signed assertions Signed responses HTTP-POST binding HTTP-Redirect binding Single Logout (SLO) chain Attribute release Encrypted assertions (roadmap)

OIDC Integration

OIDC clients use Hawiyati's standard discovery endpoint to obtain all required configuration. No manual metadata exchange is needed.

EndpointURLPurpose
Discovery/.well-known/openid-configurationFull endpoint list, algorithms, and capabilities
Authorization/oidc/authorizeStart the authorization code flow
Token/oidc/tokenExchange code for tokens or refresh
UserInfo/oidc/userinfoGet user profile claims from access token
JWKS/oidc/jwksPublic key set for token signature verification
Logout/oidc/logoutRP-initiated logout

Scope-to-claim mapping

ScopeClaims included
profilename, given_name, family_name, preferred_username, picture, locale
emailemail, email_verified
phonephone_number, phone_number_verified
addressaddress (object with formatted, street_address, locality, region, postal_code, country)

Claims are populated from user attributes stored in the session. The mapper tries multiple attribute key variants (e.g. email, mail) in order of preference.


Attribute Release

After a successful authentication, Hawiyati releases user attributes to the service provider. The set of attributes released is controlled by the SP's attribute release configuration.

For SAML, attributes appear as <saml:Attribute> elements in the AttributeStatement using urn:oasis:names:tc:SAML:2.0:attrname-format:basic. The internal routing fields principal and recipient are excluded from attribute release.

For OIDC, attributes are included as claims in the ID token and accessible via the UserInfo endpoint, scoped by the scope parameter in the authorization request.


Production Federation Checklist

#Check
1Use HTTPS public issuer/entity IDs — never localhost URLs in production metadata or redirect URIs
2Validate redirect and logout URIs strictly on the IdP side
3Rotate signing keys through a documented operational process; test SPs with the new certificate before cutover
4Test SSO and logout from both IdP-initiated and SP/RP-initiated flows
5For OIDC public clients (mobile, SPA), use PKCE with code_challenge_method=S256
6Verify your SP validates the <saml:Assertion> signature specifically, not only the outer Response
7Configure SLO endpoints if SLO is required — SPs without an SLO URL are silently skipped during logout chains

Authentication Policies

Authentication policies control what happens when a user attempts to sign in to a service provider. Each policy is a named container for ordered rules. Policies are assigned to SPs; a SP with no assigned policy allows all logins without MFA.

A policy is a named container for rules. By itself it does nothing — it must be assigned to at least one service provider.

A rule answers three questions:

  • Who — does this rule apply to everyone, or only to members of a specific group?
  • Where — does this rule apply anywhere, or only from a specific network zone?
  • When — does this rule apply at all times, or only during a configured time window?

If all conditions match, the rule's action is applied. A rule with no conditions is a catch-all — it matches every request and is typically placed last as a baseline policy.


First-Match Rule Evaluation

Rules are evaluated in priority order (lowest number first). The first matching rule wins — subsequent rules are not evaluated, even if they would also match. This is the same first-match semantics used by firewall rulesets.

If no rule matches (or the policy has no rules), the default outcome is Allow.

⚠
Rule ordering matters

Always put more specific rules (group-scoped, zone-scoped) before catch-all rules. A catch-all Allow at the top of the list will short-circuit every rule below it. Re-order rules carefully when editing policies.

AND semantics within a rule

All conditions in a rule are ANDed — every condition must match for the rule to fire. To express OR logic (e.g. "require MFA if the user is in Group A OR Group B"), create two separate rules at the same priority level.


Rule Conditions

Who (group condition)

OptionBehavior
EveryoneNo group condition. The rule applies to all users regardless of group membership.
Members of groupRule applies only when the authenticating user is a member of the selected local or LDAP-imported group. If the referenced group is deleted, the condition never matches (the rule is silently skipped).

Where (network zone condition)

OptionBehavior
AnywhereNo network condition. The rule applies regardless of the client IP address.
From network zoneRule applies only when the client IP falls within one of the zone's CIDR ranges. Network zones are named collections of IPv4 CIDR blocks managed at Admin → Network Zones.

When (time window condition)

OptionBehavior
Any timeNo time condition. The rule applies at any time of day on any day.
During time windowRule applies only when the current server time falls within the configured start/end window on the selected days. Evaluation uses the hawiyati-federation server's local system clock.
ℹ
Server timezone applies to time conditions

Time-window rules are evaluated in the server's system timezone. If the server is in a different timezone from users, schedule window times accordingly. Document the timezone in policy descriptions.


Rule Actions

ActionEffect
AllowPermit the login without requiring a second factor.
Require MFAPrompt the user for a second factor. Optionally restrict to specific methods (TOTP, FIDO2, EMAIL_OTP, SMS_OTP). Leave unchecked to accept any enrolled method.
DenyReject the login immediately with "Access denied by policy." The user cannot proceed.

When specific MFA methods are required and the user has not enrolled any of them, the login is blocked — the user cannot satisfy the requirement with an unenrolled method.


Common Policy Patterns

Require MFA for all users
Rule 1 (catch-all): Everyone / Anywhere / Any time → Require MFA

Every login to the assigned SP will require a second factor. Suitable for sensitive internal applications.

Trusted network step-up
Rule 1 (priority 1): Everyone / From zone "Office Network" / Any time → Allow Rule 2 (priority 2): Everyone / Anywhere / Any time → Require MFA

Users on the office network authenticate without MFA. Users connecting from outside are prompted for a second factor.

Privileged group strong MFA + allow others
Rule 1 (priority 1): Members of "Privileged Users" / Anywhere / Any time → Require MFA (TOTP, FIDO2) Rule 2 (priority 2): Everyone / Anywhere / Any time → Allow

The privileged group must use strong MFA. All other users are allowed without MFA. The specific rule fires first for privileged members.

Business-hours-only access
Rule 1 (priority 1): Everyone / Anywhere / During window Mon–Fri 08:00–18:00 → Allow Rule 2 (priority 2): Everyone / Anywhere / Any time → Deny

Logins are only allowed Monday to Friday, 08:00–18:00 server time. All other attempts are denied.

After-hours step-up
Rule 1 (priority 1): Everyone / Anywhere / During window Mon–Fri 08:00–18:00 → Allow Rule 2 (priority 2): Everyone / Anywhere / Any time → Require MFA

During business hours, logins succeed without MFA. Outside business hours, a second factor is required.

Emergency break-glass group
Rule 1 (priority 1): Members of "Break Glass" / Anywhere / Any time → Allow Rule 2 (priority 2): Everyone / Anywhere / Any time → Require MFA

Break-glass members can authenticate with password only. All others require MFA. Monitor audit events from this group closely.


Cache Propagation

All policy changes take effect within seconds — no service restart is required. When a policy is saved, created, deleted, or reassigned, the admin console publishes an invalidation message to the Redis sp-config:invalidate channel. The hawiyati-federation service clears its in-memory policy cache on receipt.

Network zone edits (adding or removing CIDRs) propagate via the same mechanism — you do not need to re-save policies that reference a modified zone.

ℹ
Propagation is ~10 seconds worst-case

In the rare case where the Redis pub/sub message is dropped, the in-memory cache expires naturally within a few seconds. A policy change will always be fully effective within approximately 10 seconds after saving.

The Adaptive Risk Engine

The risk engine evaluates each authentication attempt against contextual signals — behavioral and environmental factors that indicate whether a login is unusual. Based on the resulting risk score, the engine can leave the policy decision unchanged, require stronger MFA, or block access entirely.

Signals evaluated
Four parallel checks on each login: NEW_DEVICE (hwd_id cookie vs. known-device list) · GEO_VELOCITY (MaxMind GeoIP2, impossible travel) · LOGIN_VELOCITY (sliding window counter) · KNOWN_BAD_IP (threat feed / manual blocklist)
Score aggregation
Each signal contributes 0–30 points; total is capped at 100. Some signal outcomes set a minimum-level override (e.g., IMPOSSIBLE_TRAVEL forces HIGH regardless of numeric score).
Level mapping
< medium_threshold → LOW · ≥ medium_threshold → MEDIUM · ≥ high_threshold → HIGH · ≥ critical_threshold → CRITICAL. Final level = max(score level, max override level).
Risk action
LOW → ALLOW · MEDIUM → MFA_ANY · HIGH → MFA_STRONG (FIDO2 only) · CRITICAL → DENY. Configurable per-level at Admin → Risk → Level Actions.
Final decision
Strictness ordering: ALLOW < MFA_ANY < MFA_STRONG < DENY. Final access decision = stricter of (policy action, risk action). Engine runs in OFF / MONITOR / ENFORCE modes — MONITOR logs but does not block.

Risk assessment runs in parallel with policy evaluation at each login. The final access decision is always the stricter of the policy action and the risk action.

Policy actionRisk actionFinal action
AllowMFA_ANYMFA_ANY (risk is stricter)
MFA_ANYAllowMFA_ANY (policy is stricter)
MFA_STRONGDENYDENY (risk is stricter)
DENYMFA_ANYDENY (policy is stricter)

Strictness order

Actions are ranked: ALLOW < MFA_ANY < MFA_STRONG < DENY. The engine always applies the stricter one.

Risk levels and default actions

Risk levelScore rangeDefault actionUser experience
LOW< medium thresholdAllowNo change to the normal login flow
MEDIUM≥ medium thresholdMFA (any method)Prompted for any enrolled second factor
HIGH≥ high thresholdMFA (FIDO2 only)Prompted specifically for a FIDO2 hardware key or passkey
CRITICAL≥ critical thresholdDenyLogin blocked: "Access denied: risk level too high"

Default level actions can be overridden per-level at Admin → Risk → Level Actions.


Risk Signals

Four signals are evaluated on each login. Each can be independently enabled, disabled, and configured with a fail mode.

NEW_DEVICE hwd_id cookie

Detects logins from an unrecognized browser or device. Hawiyati issues a hwd_id cookie (UUID, 400-day lifetime) to each browser. On each login, the cookie is checked against the user's known-device list.

  • KNOWN_DEVICE — No additional risk (0 points). Device is in the trusted list.
  • NEW_DEVICE — Unrecognized device for a user with at least one known device on record. Contributes MEDIUM risk.
  • DEVICE_TRUST_EXPIRED — Device was trusted but the trust window has lapsed. Contributes MEDIUM risk.
  • REVOKED_DEVICE_SEEN — An administrator-revoked device has reappeared. Contributes HIGH risk.

Skipped for users with no known devices on record (enrollment baseline — first login never raises this signal).

GEO_VELOCITY MaxMind GeoIP

Detects logins from physically implausible locations relative to the user's recent activity. Requires a MaxMind-compatible GeoIP2 database file — not included; must be licensed separately.

  • GEO_OK — Location consistent with history (0 points).
  • NEW_COUNTRY — Login from a country the user has not previously authenticated from. Contributes MEDIUM risk.
  • IMPOSSIBLE_TRAVEL — Implied travel speed since the last known login exceeds maxTravelKmh (default 900 km/h). Contributes HIGH risk with a HIGH minimum-level override.

Skipped for private/reserved IPs, when the GeoIP database is not loaded, or when no previous login location is on record.

LOGIN_VELOCITY Sliding window

Detects brute-force and credential-stuffing attacks by counting recent failed logins. Default window: 15 minutes.

  • USER_FAILED_HIGH — This username had ≥ 5 failed logins within the window.
  • IP_FAILED_HIGH — This IP had ≥ 10 failed logins for any username within the window.
  • IP_MANY_USERS — This IP attempted ≥ 5 distinct usernames within the window (credential stuffing indicator).

All three factors are independent and can fire simultaneously. Combined score for this signal capped at 30 points.

IP_REPUTATION Admin-imported blocklist

Matches the client IP against an administrator-imported list of known-bad CIDR ranges. Hawiyati does not ship with any pre-loaded blocklist data.

  • KNOWN_MALICIOUS_IP, CREDENTIAL_STUFFING_IP, TOR_EXIT, ANON_PROXY, DATACENTER, OTHER

Each category has independently configurable points and minimum-level overrides. Returns clean if no blocklist has been imported.

Signal fail modes

Fail modeBehavior on error
OPEN (default)Signal is skipped — contributes no points. Assessment continues with remaining signals. Use when availability matters more than conservative security (e.g. GEO_VELOCITY if the GeoIP database is sometimes unavailable).
CLOSEDSignal contributes a HIGH minimum-level override. Access requires FIDO2 MFA until the error is resolved. Use for security-critical signals like IP_REPUTATION.

Scoring & Risk Levels

Each signal evaluates the request and contributes 0–30 points. Points are summed across all enabled signals and capped at 100. The total score is then mapped to a risk level using configurable thresholds.

ℹ
Minimum-level overrides take precedence

Some signal factors set a minimum-level override — this forces the risk level to be at least that value regardless of the numeric score. For example, IMPOSSIBLE_TRAVEL always forces HIGH, even if the total score would map to MEDIUM.

Scoring pipeline
For each enabled signal: evaluate(request) → factor + points + optional min-level-override Sum all points → cap at 100 Apply min-level-override (take highest across all signals) Map score to level: < medium_threshold → LOW < high_threshold → MEDIUM < critical_threshold → HIGH ≥ critical_threshold → CRITICAL Final level = max(score_level, max_override_level) Map level to action (using Level Actions config): LOW → ALLOW MEDIUM → MFA_ANY HIGH → MFA_STRONG CRITICAL → DENY

Engine Modes

ModeBehaviorTypical use
OFF Risk assessment is skipped entirely. No signals evaluated. No overhead. Development, initial deployment, explicit opt-out
MONITOR Signals are evaluated and assessments are recorded, but the risk action never overrides the policy action. Users are not blocked or stepped up by the risk engine. Pre-enforcement tuning; measuring would-have-blocked rate
ENFORCE The risk action overrides the policy action when stricter. This is the production operating mode. Production with tuned thresholds
✓
Recommended rollout: MONITOR first

Start in MONITOR, review the dashboard daily for several days of real traffic. The "would have step-up or block" metric shows the impact ENFORCE mode would have had without affecting users. Tune thresholds until the false-positive rate is acceptable, then switch to ENFORCE.


Risk Engine Configuration

Score thresholds

Configured at Admin → Risk → Settings → Thresholds. Thresholds must be strictly ascending (medium < high < critical). Any score below the medium threshold maps to LOW.

Tuning parameters

ParameterDefaultDescription
maxTravelKmh900Speed above which GEO_VELOCITY fires IMPOSSIBLE_TRAVEL. 900 km/h ≈ commercial jet speed.
loginVelocityWindowMinutes15Sliding window for failed-login counting.
loginVelocityUserFailThreshold5Per-user failure count that triggers USER_FAILED_HIGH.
loginVelocityIpFailThreshold10Per-IP failure count that triggers IP_FAILED_HIGH.
loginVelocityIpUserThreshold5Distinct usernames per IP that triggers IP_MANY_USERS.
storeIpModeRAWRAW: full IP stored. TRUNCATED: last octet/64 bits zeroed for privacy compliance.

IP reputation blocklist management

Import blocklists at Admin → Risk → IP Reputation. Format: one CIDR per line; lines starting with # are comments. Supported categories: KNOWN_MALICIOUS, CREDENTIAL_STUFFING, TOR_EXIT, ANON_PROXY, DATACENTER, OTHER.

Use the Dry Run button to preview the import before committing. Use Replace with the same source label for feed refreshes. Entries expire automatically after their expiresAt date (default 30 days from import).

GeoIP database

Configure the filesystem path to a MaxMind-compatible .mmdb file at Admin → Risk → Settings → GeoIP Database. Hawiyati computes and stores a SHA-256 checksum of the file to detect unexpected replacements. Use Admin → Risk → GeoIP Test to verify a lookup before enabling the GEO_VELOCITY signal.


Risk Engine Operations Guidance

ScenarioRecommendation
Starting risk enforcement for the first time Start in MONITOR. Review dashboard daily. Tune until the "would-have-blocked" rate is acceptable. Then switch to ENFORCE.
High false-positive rate on GEO_VELOCITY If users frequently travel internationally, increase maxTravelKmh or reduce NEW_COUNTRY signal weight. Consider setting GEO_VELOCITY fail mode to OPEN if the GeoIP database availability is unreliable.
Suspicious device seen Revoke the device in Admin → Risk → Devices. Revoking marks it so any future appearance raises a HIGH signal. Do not delete — deletion removes the history.
Refreshing IP blocklist feeds Re-import with Replace checked and the same source label. Use a regular cadence (e.g. weekly) since IP reputation data ages quickly. Expired entries stop matching automatically.
New signal rollout Enable the signal in MONITOR mode first. The dashboard shows its contribution without user impact. Move to ENFORCE only after validating the signal's quality against real traffic.
Emergency access after enforcement problems Switch risk mode to MONITOR or OFF at Admin → Risk → Settings. This takes effect within seconds via Redis pub/sub — no restart required. Document and review the bypass window in the audit log.
ℹ
MONITOR mode assessments are permanent records

Even in MONITOR mode, every risk assessment is stored in the risk assessment event table (not the main audit event table, but visible in Admin → Risk → Dashboard). These records feed the "would have challenged" metrics and are retained for the configured lookback window.

HawiyatiDocumentation · v2026 · Spring Boot 3.5