Authentication Protocols and Federated IdentityIntroduction and ContextModern applications rarely authenticate every user with a password database owned by the application itself. Employees may sign in through an organisation’s directory, customers may use an external identity provider, and a mobile application may access several APIs on a user’s behalf. These arrangements require protocols that distinguish identity, authentication, authorisation, session management, and trust. Authentication answers who is the subject? Authorisation answers what is the subject allowed to do? A protocol such as OAuth 2.0 primarily supports delegated authorisation, whereas OpenID Connect (OIDC) adds an identity layer. SAML provides federated authentication and authorisation assertions, particularly in enterprise web environments. Kerberos provides ticket-based authentication within trusted realms, while LDAP commonly supplies directory storage and query services rather than a complete modern web-login protocol. Federated identity allows one organisation or service to rely on another organisation’s identity provider (IdP). The relying party (RP), service provider (SP), or client application does not necessarily verify the user’s password itself. Instead, it validates a protocol response issued by a trusted IdP. Learning ObjectivesBy the end of this chapter, you should be able to: - distinguish authentication, authorisation, accounting, sessions, and identity federation;
- design secure server-side sessions and explain cookie protections;
- describe OAuth 2.0 and the security direction of OAuth 2.1;
- implement the authorisation-code flow with PKCE safely;
- explain OIDC discovery, ID tokens, claims, nonce, and token validation;
- compare SAML, Kerberos, LDAP, OAuth, and OIDC;
- integrate an application with an identity provider;
- validate tokens and assertions without confusing authentication with authorisation;
- identify protocol misuse, including token substitution, CSRF, redirect-uri attacks, and confused-deputy problems;
- evaluate governance, privacy, availability, and operational consequences of federation.
1. A Conceptual Model of Identity SystemsA useful identity architecture contains five related functions: - Identification: a subject presents an identifier, such as an email address or account name.
- Authentication: evidence is checked, such as a password, passkey, certificate, or Kerberos ticket.
- Session management: the application maintains continuity after authentication, commonly with a server-side session identifier.
- Authorisation: policies determine whether the subject may perform an action on a resource.
- Federation: one security domain accepts identity information issued by another domain.
A principal may be a human user, service account, device, or workload. A claim is a statement about a principal, such as an identifier, group, or authentication time. An assertion is a security protocol message containing claims and metadata. A token is a structured or opaque artefact used to convey authority or identity. The security boundary is important. An access token is intended for a resource server; an ID token is intended for the client that requested authentication. Presenting an ID token to an API as though it were an access token is a common and serious design error. Trust relationshipsFederated systems are built on explicit trust: - the application trusts a particular issuer;
- the issuer signs or otherwise protects protocol messages;
- the application knows the permitted audience and endpoints;
- keys, metadata, certificates, and configuration are managed securely;
- administrators decide which claims may influence access.
Trust is not created merely because a token is syntactically valid. A validly signed token from the wrong issuer or intended for a different audience must be rejected. 2. Sessions and CookiesA traditional web session works as follows. The user authenticates, the server creates a random session identifier, and the browser stores it in a cookie. On subsequent requests the browser sends the cookie, allowing the server to retrieve session state. A secure session identifier should be generated with a cryptographically secure random generator and should be unpredictable. It should not encode user information or permissions. Session state normally includes the authenticated subject, authentication time, privilege level, expiry information, and possibly reauthentication requirements. Important cookie attributes include: | Attribute | Purpose |
|---|
Secure | Sends the cookie only over HTTPS. | HttpOnly | Prevents ordinary JavaScript from reading the cookie. It does not stop all cross-site scripting consequences. | SameSite | Controls cross-site cookie sending and reduces CSRF exposure. | Domain and Path | Restrict where the browser sends the cookie. Narrow scope is safer. | Max-Age or Expires | Defines persistence or lifetime. |
At login, the server should rotate the session identifier. This prevents session fixation, in which an attacker causes a victim to use a session identifier known to the attacker. Sessions should also be invalidated on logout, password recovery, suspicious changes, and administrative revocation where appropriate. Absolute and idle timeouts should reflect risk rather than convenience alone. A server-side session is often safer and easier to revoke than a large self-contained browser token. However, it requires shared session storage or careful routing in a horizontally scaled deployment. Distributed caches must themselves be protected, and logout semantics must be defined across devices and applications. CSRF and XSSCookie-authenticated state-changing requests require CSRF protection when a cross-site request could cause harm. Common defences include SameSite cookies, unpredictable anti-CSRF tokens, origin checking, and requiring a custom request header for APIs. CSRF tokens do not repair cross-site scripting (XSS); an XSS attacker may act within the victim’s authenticated browser. Output encoding, input handling, content security policy, dependency management, and secure development practices remain necessary. 3. OAuth 2.0 and OAuth 2.1OAuth 2.0 is a framework for delegated authorisation. It allows a resource owner to grant a client limited access to a protected resource without disclosing the resource owner’s password to the client. The principal roles are: - Resource owner: usually the user who controls data.
- Client: the application requesting access.
- Authorisation server: issues authorisation codes and tokens.
- Resource server: hosts protected APIs and validates access tokens.
An access token represents authority to access specified resources. It may be opaque or structured, such as a JWT. The API must decide how to validate it: introspection, local signature verification, or another trusted mechanism. Authorisation-code flow with PKCEThe recommended browser and mobile pattern is the authorisation-code flow with Proof Key for Code Exchange (PKCE). The client generates a high-entropy code_verifier, derives a code_challenge, and sends the challenge in the authorisation request. After the user authenticates, the authorisation server returns a short-lived code to the registered redirect URI. The client sends the code and verifier to the token endpoint. The server issues tokens only if the verifier matches the original challenge. For the usual S256 method, the transformation is: codechallenge = BASE64URL(SHA-256(codeverifier)) code_verifier is a randomly generated string with suitable length and character restrictions; SHA-256 is the cryptographic hash function; and BASE64URL is unpadded base64url encoding. The values are compared according to the PKCE specification. PKCE protects an intercepted authorisation code from being redeemed by an attacker who lacks the verifier.
The high-level sequence is: - The client creates
state and a PKCE verifier. - The client sends the browser to the authorisation endpoint.
- The user authenticates and grants consent, if required.
- The authorisation server redirects the browser with a code and state.
- The client verifies
state and exchanges the code plus verifier. - The resource server receives an access token and validates it.
state binds the response to the initiating browser transaction and helps prevent login CSRF. It must be unpredictable and associated with the user’s transaction. PKCE and state solve related but different problems; one should not casually be treated as a universal replacement for the other.
OAuth clients must use exact, pre-registered redirect URIs wherever possible. Wildcard redirect URIs, open redirects, implicit token delivery in the URL fragment, and resource-owner-password credentials are discouraged or removed from modern security guidance. OAuth 2.1 is best understood as a consolidation of current OAuth security practices, including stronger use of PKCE and removal of historically unsafe patterns; implementers should check the current status of the relevant standards rather than assume a final specification number guarantees security. Access-token designAn access token should be narrowly scoped, audience-restricted, short-lived where practical, and transmitted only through protected channels. The API should enforce scopes and resource-specific policy rather than accepting any token issued by a trusted provider. Bearer tokens require special care because possession is sufficient for use. They should not be placed in URLs, logs, browser history, or error messages. TLS protects tokens in transit but does not protect against malicious application code, compromised logs, or an API that fails to validate claims. Refresh tokens have greater longevity and therefore require stronger protection. Rotation, reuse detection, secure storage, and revocation strategies are important. Public clients should not pretend that a static client secret is confidential when it is embedded in downloadable software. 4. OpenID ConnectOpenID Connect is an identity protocol built on OAuth 2.0. It introduces the ID token, normally a signed JWT, and standardises identity claims and discovery. OIDC answers the question: “Which authenticated user completed this authentication transaction for this client?” An ID token commonly contains claims such as: iss: issuer;sub: stable subject identifier within the issuer and client context;aud: intended audience, normally the client identifier;exp: expiration time;iat: issue time;nonce: value binding the token to the initiating authentication request;auth_time: time of authentication, when supplied;- authentication-context or assurance claims, where supported.
The client must validate the signature using trusted issuer keys, confirm iss, confirm that its client identifier appears in aud, check exp and relevant time constraints, and compare the returned nonce with the transaction nonce. If multiple audiences exist, azp may also be relevant under OIDC rules. The client must not accept an arbitrary algorithm, issuer, or key supplied by the token itself. Discovery and key rotationOIDC discovery publishes metadata such as the issuer, authorisation endpoint, token endpoint, user-information endpoint, supported algorithms, and JSON Web Key Set (JWKS) location. Discovery reduces manual configuration but creates a configuration trust dependency. Applications should validate that the discovered issuer matches the expected issuer and should handle signing-key rotation by refreshing keys safely without blindly accepting attacker-controlled endpoints. A UserInfo endpoint can return claims about the subject when called with an access token. The application must verify that the UserInfo sub matches the authenticated subject represented by the ID token. Claims from an external IdP should be mapped deliberately to local roles; an arbitrary email, group, or admin claim should not automatically create high privilege. OIDC versus OAuthOAuth access tokens authorise API access. OIDC ID tokens communicate authentication results to the client. OAuth alone does not define a universal login token. A provider may issue both tokens in an OIDC flow, but they have different audiences, purposes, and validation rules. 5. SAML 2.0 FederationSecurity Assertion Markup Language (SAML) 2.0 is an XML-based framework widely used for enterprise single sign-on. In a common web browser SSO profile, the employee visits an SP, is redirected to an IdP, authenticates there, and returns with a signed SAML response containing an assertion. The assertion may contain: - a subject identifier;
- authentication statements;
- attribute statements;
- conditions, including validity times;
- audience restrictions;
- an intended recipient or assertion-consumer service (ACS);
- an identifier linking the response to a request.
The SP must validate the XML signature using a trusted certificate or key, verify the issuer, destination, audience, recipient, time conditions, and request correlation where applicable. XML signature wrapping attacks demonstrate why applications must use a mature, correctly configured SAML library and must ensure that the signed assertion is the assertion actually processed. SAML’s strengths include mature enterprise federation, rich metadata, and established browser SSO. Its challenges include XML complexity, certificate rollover, verbose messages, browser-dependent flows, and difficult interoperability debugging. SAML attributes also require careful mapping: an IdP’s group name may not have the same meaning as an application role. 6. Kerberos and LDAPKerberosKerberos is a network authentication protocol based on symmetric cryptography and trusted time. A Key Distribution Center (KDC) contains an Authentication Server and Ticket-Granting Server. After initial authentication, a client obtains a ticket-granting ticket (TGT), then requests a service ticket for a particular service principal. The client presents the service ticket to the service, often with an authenticator demonstrating freshness. Kerberos avoids sending the user’s password to every service. It supports mutual authentication and single sign-on within a realm or cross-realm trust arrangement. Its dependencies include secure key management, accurate clocks, reliable KDC availability, correct service-principal names, and careful delegation configuration. Kerberos is common in enterprise operating-system domains, but it is not itself a replacement for browser federation across unrelated organisations. LDAPLDAP is a directory access protocol. A directory stores entries identified by distinguished names and attributes, often in a hierarchical namespace. LDAP operations include bind, search, compare, modify, and extended operations. An application may authenticate a user by binding to LDAP, but this does not automatically provide modern web SSO, multifactor authentication, token issuance, or delegated API authorisation. LDAP integration requires TLS, certificate validation, least-privilege service accounts, safe search filters, input handling, connection limits, and careful treatment of directory availability. Passwords should not be transmitted through unprotected simple binds. Applications should avoid copying excessive directory data into local systems and should define how disabled accounts and group changes affect existing sessions. 7. Single Sign-On and Identity-Provider IntegrationSingle sign-on (SSO) means that a user authenticates once, or reuses an established IdP session, to access multiple relying applications. SSO improves usability and centralises authentication controls, but it also increases the impact of IdP compromise or outage. A disciplined integration process includes: - Define the trust: identify the issuer, tenant, metadata source, signing keys, endpoints, audiences, and approved flows.
- Register the application: use exact redirect URIs, appropriate client type, permitted scopes, and secure credentials.
- Select subject identifiers: prefer stable, non-reassignable identifiers rather than mutable email addresses.
- Map claims: document how issuer claims become local user records, groups, and roles.
- Validate protocol messages: implement signature, issuer, audience, lifetime, nonce/state, and correlation checks.
- Protect local sessions: federation does not remove the need for secure cookies, session rotation, logout policy, and reauthentication.
- Plan lifecycle events: account creation, linking, disabling, role changes, offboarding, and recovery require explicit rules.
- Monitor and test: log decisions without recording secrets, alert on anomalous issuer or key changes, and test negative cases.
Account linking is especially sensitive. Automatically linking an existing local account merely because an incoming email matches can permit account takeover when email ownership, verification status, or tenant context is misunderstood. Linking should require a trusted verified claim and, for high-risk accounts, an existing authenticated session or additional verification. 8. Token and Assertion ValidationValidation is a chain of independent checks, not simply “verify the signature.” A practical sequence is: - parse defensively and reject malformed input;
- obtain keys only from a trusted configuration or validated discovery document;
- restrict accepted algorithms and key types;
- verify the signature or use secure introspection;
- check the expected issuer exactly;
- check audience and, where relevant, authorised party;
- check expiration, not-before, issue time, and acceptable clock skew;
- check nonce, state, code verifier, response correlation, or SAML request identifiers as applicable;
- enforce scopes, roles, tenant, resource, and local policy;
- reject replay where the protocol and risk require it;
- record security-relevant events without exposing token contents unnecessarily.
The receiving component must know what it is validating. A frontend may validate an ID token for display decisions, but a backend API must enforce access independently. A decoded JWT is not a validated JWT. Base64url decoding reveals content; it does not establish authenticity. Clock tolerance should be small and operationally justified. Excessive tolerance weakens expiry controls, while no tolerance causes failures when systems’ clocks differ. Synchronisation services should be monitored because time is a security dependency in Kerberos, JWT validation, and SAML conditions. 9. Protocol Misuse and DefencesCommon failure patterns- Open redirect and weak redirect URI matching: an attacker obtains a code or token at an attacker-controlled endpoint. Use exact registration and eliminate open redirects.
- Login CSRF: a victim is silently logged into an attacker-controlled account. Bind the response using
state, use appropriate browser protections, and test the complete flow. - Code interception: a stolen authorisation code is redeemed. Use PKCE and short-lived, single-use codes.
- Token substitution: a token from another issuer, client, or API is accepted. Validate issuer and audience.
- Algorithm confusion or acceptance of
none: an implementation accepts an unintended signing mode. Pin algorithms and use a trusted library. - ID-token-as-access-token: an API accepts a token whose audience is the client rather than the API. Require the API’s audience and appropriate scopes.
- Overprivileged scopes and claims: broad permissions remain long after their need. Use least privilege and short lifetimes.
- Bearer-token leakage: tokens appear in URLs, referrers, logs, screenshots, or client storage. Use headers, redaction, secure storage, and appropriate browser architecture.
- Improper logout assumptions: local logout is mistaken for global IdP logout. Define local, federated, and session-revocation behaviour explicitly.
- Tenant confusion: a valid identity from one tenant is accepted in another. Bind tenant context to the issuer, client registration, subject, and policy.
Threat modelling should consider browser, mobile, API, service-to-service, and machine-to-machine contexts separately. A pattern secure for a confidential server application may be unsuitable for a public mobile client. 10. Applied Case: University Research PortalThe following is an illustrative case. A university operates a research portal containing grant data and laboratory documents. Staff already authenticate through the university IdP, which supports SAML and OIDC. External collaborators belong to partner institutions. The portal exposes an API used by a web frontend and a mobile field application. ProblemThe first implementation accepted any JWT signed by a cloud key endpoint, mapped the email claim directly to an account, and treated an ID token as an API credential. Redirect URIs included a wildcard. A departing researcher retained access because local sessions were never re-evaluated. AnalysisThe design had four trust errors. It trusted keys without first binding them to an expected issuer; it confused identity claims with authorisation; it failed to distinguish token audiences; and it treated authentication as a one-time event rather than a lifecycle. The wildcard redirect also enlarged the attack surface. ApproachThe university registered separate OIDC clients for the web and mobile applications. The web client used the authorisation-code flow with PKCE, exact redirect URIs, state, and nonce. The API accepted only access tokens whose issuer was the university IdP, audience was the research API, lifetime was valid, and scopes matched the requested operation. The mobile client used a public-client design with PKCE and secure operating-system storage for refresh material. Stable subject identifiers, not email addresses, became the account-linking key. Email was retained as a display and communication attribute. Roles were assigned from an approved claim namespace and then checked against local project membership. The API used tenant and project policy in addition to scopes. Key discovery was pinned to the expected issuer metadata, and key rotation was tested. For higher-risk grant operations, the portal required recent authentication and step-up multifactor authentication. Sessions were rotated at login, had idle and absolute timeouts, and were revoked when the university marked an account inactive. Audit logs recorded issuer, subject, client, action, decision, and correlation identifier, while excluding raw tokens. OutcomeThe revised design separated authentication, token validation, and authorisation. Partner federation could be added through approved trust relationships without weakening the API boundary. Offboarding became effective within a defined operational interval, and security testing could exercise each validation rule independently. Learning pointsFederation reduces duplicated passwords but does not eliminate application responsibility. A trustworthy identity provider cannot compensate for an API that accepts the wrong token. Stable identifiers, exact audience checks, least privilege, lifecycle controls, and clear ownership are as important as selecting a protocol. 11. Governance, Privacy, and Professional PracticeIdentity systems process sensitive personal information. Data minimisation requires collecting only claims needed for a stated purpose. A relying party should not request broad profile scopes merely because they are available. Retention schedules, access controls, breach procedures, and data-subject rights may be governed by institutional policy and applicable privacy law. Centralised SSO creates concentration risk. An IdP outage can affect many applications, while a compromised signing key can have broad consequences. Organisations should maintain emergency access procedures, key-rotation plans, tested backups, incident contacts, and dependency monitoring. Break-glass accounts require strong protection and continuous review. AI-assisted development can generate insecure authentication code, especially around JWT verification, redirect handling, and cryptographic configuration. Generated code must be reviewed against current standards, tested with malicious inputs, and checked for library-version and deployment assumptions. AI systems should not receive production tokens, private keys, or unnecessary personal data. Best-Practice Checklist- Use HTTPS and validated certificates for all protocol endpoints.
- Prefer authorisation code plus PKCE for browser and mobile clients.
- Use OIDC for login identity and OAuth access tokens for APIs.
- Validate issuer, audience, signature, time, nonce, state, and relevant correlation values.
- Use exact redirect URIs and remove open redirects.
- Keep access tokens scoped and short-lived; protect and rotate refresh tokens.
- Use stable subject identifiers and deliberate claim-to-role mappings.
- Protect sessions with secure cookies, rotation, timeouts, and revocation procedures.
- Use mature SAML, Kerberos, and JWT libraries rather than implementing cryptography or XML security yourself.
- Monitor key rotation, clock synchronisation, IdP availability, and anomalous authentication events.
- Test negative cases: wrong issuer, wrong audience, expired token, altered signature, replay, missing nonce, and disabled user.
Chapter SummaryAuthentication protocols solve different problems. Sessions maintain application continuity; OAuth 2.0 delegates access to resources; OIDC adds standardised identity authentication; SAML enables enterprise browser federation; Kerberos supplies ticket-based authentication within trusted realms; and LDAP provides directory access rather than complete web SSO. Secure integration depends on explicit trust, exact redirect handling, PKCE, state and nonce binding, careful token and assertion validation, audience and issuer checks, least privilege, and lifecycle management. Federation improves usability and centralises controls, but it also introduces dependency, privacy, key-management, and concentration risks. The most reliable design treats every token as a security decision requiring independent validation and local authorisation policy. Key TermsAuthentication: Verification of a subject’s identity. Authorisation: Decision about permitted actions on resources. Access token: Credential presented to a resource server to request protected access. ID token: OIDC token communicating an authentication result to a client. Assertion: Security statement about a principal, commonly used in SAML. Identity provider (IdP): System that authenticates subjects and issues identity information. Relying party (RP): Application relying on an IdP’s OIDC identity result. Service provider (SP): Application participating in SAML federation. OAuth client: Application requesting delegated authorisation. Resource server: API that protects resources and validates access tokens. PKCE: Mechanism binding an authorisation code to a client-generated verifier. Issuer: Entity identified as the authority that issued a token or assertion. Audience: Intended recipient of a token or assertion. Nonce: Value binding an OIDC response to an authentication request. State: Client-generated value correlating an authorisation response with a browser transaction. Kerberos realm: Administrative domain containing Kerberos principals and a KDC. LDAP: Directory access protocol used to query and manage directory entries. Single sign-on: Access to multiple applications using a shared or reusable authentication event. Federated identity: Identity arrangement in which one security domain relies on another. Session fixation: Attack in which a victim is induced to use an attacker-known session identifier. Review Questions5 Short Answer Questions- What is the principal difference between an OAuth access token and an OIDC ID token?
- Why should a session identifier be rotated after authentication?
- What security problem does PKCE address?
- Name four claims or properties that should be checked when validating an OIDC ID token.
- Why is LDAP not, by itself, a complete modern web SSO protocol?
5 Long Answer Questions- Explain the authorisation-code flow with PKCE, including the roles of the client, authorisation server, and resource server.
- Compare SAML, OIDC, Kerberos, and LDAP in terms of purpose, message style, deployment context, and operational challenges.
- Describe a secure identity-provider integration process for a multi-tenant web application.
- Explain how secure cookies, CSRF controls, session rotation, and logout policy work together in session management.
- Discuss the governance and privacy risks created by centralised single sign-on and propose controls.
3 Analytical / Application Questions- An API accepts a correctly signed JWT, but its audience is the frontend client rather than the API. Analyse why accepting it is unsafe and specify the validation and architecture changes required.
- A university wants to allow partner institutions to access a research portal using SAML while its mobile application uses OIDC. Design a federation and authorisation architecture, including claim mapping, account linking, token validation, and offboarding.
- During an incident, logs reveal access tokens in URLs and a wildcard redirect URI. Prioritise the response, explain the likely attack paths, and recommend both immediate containment and long-term remediation.
Multiple Choice Questions with AnswersQuestion 1Which protocol layer primarily adds standardised user authentication and ID tokens to OAuth 2.0? A. LDAP B. OpenID Connect C. Kerberos D. SAML metadata exchange Correct Answer: B. OpenID Connect Question 2What is the main purpose of PKCE in the OAuth authorisation-code flow? A. To encrypt all API responses B. To bind an authorisation code to the client that initiated the request C. To replace issuer validation D. To create a directory user account Correct Answer: B. To bind an authorisation code to the client that initiated the request Question 3Which check determines whether a token was issued for the API receiving it? A. Audience validation B. Cookie Path validation C. LDAP search validation D. Browser language validation Correct Answer: A. Audience validation Question 4Which statement about an OIDC ID token is correct? A. It is always intended to be presented to every API B. It communicates an authentication result to the OIDC client C. It replaces the need for an access token in all cases D. It is an LDAP directory entry Correct Answer: B. It communicates an authentication result to the OIDC client Question 5Which cookie attribute prevents ordinary JavaScript from reading a session cookie? A. Secure B. SameSite C. HttpOnly D. Max-Age Correct Answer: C. HttpOnly Question 6What is LDAP primarily designed to provide? A. Directory access and queries B. Delegated API authorisation scopes C. OIDC nonce validation D. Browser redirect binding Correct Answer: A. Directory access and queries Question 7Which technology uses tickets and a trusted time source for authentication within a realm? A. OAuth B. SAML C. Kerberos D. PKCE Correct Answer: C. Kerberos Question 8Why should an application reject a correctly signed token from an unexpected issuer? A. A valid signature alone does not establish that the issuer is trusted for this application B. Signed tokens cannot contain claims C. Unexpected issuers always indicate expired tokens D. Issuer checks are needed only for LDAP Correct Answer: A. A valid signature alone does not establish that the issuer is trusted for this application Question 9Which practice most directly reduces authorisation-code interception risk? A. Using a wildcard redirect URI B. Using PKCE with a high-entropy verifier C. Putting the code in an API log D. Accepting any signing algorithm Correct Answer: B. Using PKCE with a high-entropy verifier Question 10What is a major risk of mapping an incoming email claim directly to a privileged local account? A. It prevents TLS from operating B. Email addresses are always cryptographic keys C. Mutable or insufficiently verified identifiers can enable account takeover or incorrect linking D. It disables Kerberos tickets Correct Answer: C. Mutable or insufficiently verified identifiers can enable account takeover or incorrect linking
|