Secure Software Development and Code Analysis

Chapter 7
Identity, Session and Access-Control Security

Post Graduate Program in Cyber Security
Secure Software Development and Code Analysis   •   Post Graduate

7. Identity, Session and Access-Control Security

Introduction and Context

Identity and access control form the security boundary of most software systems. Encryption may protect data in transit and validation may protect an application from malformed input, but neither can answer a central question: who is permitted to perform a particular action on a particular resource under particular conditions? Identity security addresses the reliable representation and verification of users, services, devices, and organizations. Access-control security determines what authenticated subjects may do. Session security preserves that decision across a sequence of requests without allowing an attacker to impersonate the subject.

These concerns are closely related but should not be treated as interchangeable. Authentication establishes identity or demonstrates control of an authenticator. Authorization evaluates permissions. Accounting records relevant activity. A system that authenticates users correctly may still be insecure if it assigns excessive privileges, accepts forged tokens, fails to revoke sessions, or confuses a user’s identity with the user’s current authority.

In contemporary systems, identity is distributed across browsers, mobile applications, APIs, cloud platforms, identity providers, service accounts, and third-party federation protocols. This distribution creates operational benefits but also introduces trust relationships, token-handling risks, lifecycle problems, and policy complexity. Secure development therefore requires identity controls to be designed as part of the application architecture rather than added after functionality has been implemented.

Learning Objectives

After completing this chapter, the reader should be able to:

1. Distinguish identification, authentication, authorization, accounting, and federation.

2. Design secure identity lifecycles, password storage, credential recovery, and key-handling processes.

3. Explain multifactor authentication and evaluate its resistance to common attacks.

4. Implement secure browser and API session management.

5. Compare RBAC, ABAC, and policy-based access-control models.

6. Assess OAuth 2.0, OpenID Connect, federation, and token-based architectures.

7. Diagnose common authentication and authorization failures.

8. Apply governance, privacy, and professional principles to identity systems.

Identity as a Lifecycle

An identity is a managed representation of a person, workload, device, or organization. Identity management begins before the first login and continues after access has been removed. A useful lifecycle includes proofing, provisioning, authentication, authorization, monitoring, review, suspension, and deprovisioning.

Identity proofing establishes confidence that an account corresponds to the claimed subject. The strength of proofing should reflect the consequences of compromise. A public discussion forum may require only verified email ownership, whereas a financial administration account may require organizational verification and stronger evidence. Proofing should avoid collecting unnecessary personal data because identity systems are attractive targets and can create substantial privacy harm.

Provisioning creates accounts and assigns initial attributes, groups, roles, or entitlements. In organizations, joiner–mover–leaver processes are particularly important. A joiner receives appropriate access when joining; a mover has permissions recalculated when changing role; a leaver loses access promptly when employment or contractual authority ends. Static account creation without corresponding removal is a major source of privilege accumulation.

Authentication verifies possession, knowledge, inherence, or an approved combination of these factors. Authorization then maps the authenticated subject to permitted actions. Periodic access reviews, risk-based monitoring, and event logging support continuing assurance. Deprovisioning must revoke active sessions, refresh tokens, API keys, certificates, and delegated grants—not merely disable a directory account.

Non-human identities require the same lifecycle discipline. Service accounts, workload identities, CI/CD credentials, signing keys, and machine certificates should have an owner, purpose, scope, expiry or rotation process, and monitoring. Shared administrative accounts weaken accountability and should be avoided except where a controlled technical necessity exists.

Authentication Foundations

Identification is a claim, such as a username or email address. Authentication is the process of testing that claim. Authorization is the decision to allow or deny an operation. Accounting, often called auditing or accountability, records who performed an action, when, from where, and with what result. These functions are conceptually distinct even when implemented by one identity platform.

Authentication factors are commonly grouped as something the user knows, has, or is. Passwords and PINs are knowledge factors. Hardware security keys, smart cards, and authenticator applications are possession factors. Fingerprints and facial characteristics are inherence factors. Location, device posture, and behavioral patterns are useful risk signals but should not automatically be treated as independent authentication factors.

Multifactor authentication requires more than one independent factor. Combining a password with a second password is not MFA. A one-time code sent by SMS can improve security over passwords alone, but it is vulnerable to SIM replacement, number porting, interception, and social engineering. Time-based one-time passwords are stronger than static passwords but remain susceptible to phishing because a user can be persuaded to disclose the current code. WebAuthn and FIDO2 security keys provide phishing-resistant authentication by binding credentials to the legitimate origin. For high-risk operations, phishing-resistant methods should be preferred.

Authentication recovery is part of authentication security. Weak security questions, predictable reset links, support-desk impersonation, or indefinite recovery tokens can bypass strong login controls. Recovery tokens should be random, single-use, short-lived, protected in transit, and invalidated after use. High-impact recovery should trigger notification, reauthentication, and, where appropriate, human review.

Passwords, Secrets, and Cryptographic Keys

Passwords should never be stored in plaintext or with reversible encryption. A password verifier should use a slow, memory-hard password hashing function such as Argon2id, with a unique random salt for each password. The salt prevents identical passwords from producing identical stored values and makes precomputed rainbow-table attacks less useful. A server-side pepper may provide an additional defense if stored separately in a secrets manager or hardware security module, although it does not replace appropriate password hashing.

Password policy should emphasize length, uniqueness, breached-password screening, and resistance to automated guessing rather than arbitrary complexity rules that encourage predictable substitutions. Rate limiting, progressive delays, anomaly detection, and account protection should be implemented carefully so that attackers cannot easily cause denial of service against legitimate users. Error messages should not reveal whether an account exists.

Secrets include passwords, API keys, signing keys, encryption keys, certificates, and tokens. They should not be embedded in source code, container images, client-side applications, or ordinary log files. A secrets-management system should control access, record use, support rotation, and separate duties. Keys should have a defined purpose and algorithm, appropriate length, limited exposure, and a documented replacement process. Encryption keys and signing keys are not interchangeable: confidentiality keys protect secrecy, whereas signing keys provide integrity and authenticity.

Key rotation reduces the impact of compromise but cannot compensate for unrestricted access or poor incident response. Applications must be able to recognize key versions, support overlapping validity during planned rotation, and revoke or quarantine compromised keys. Private keys should be generated and used in protected environments whenever feasible.

Sessions: Maintaining Trust Across Requests

HTTP is stateless, so applications commonly create a session after authentication. A session identifier is a bearer credential: whoever possesses it may be treated as the user. Consequently, a session identifier should be generated using a cryptographically secure random source, contain no meaningful user data, and be transmitted only over TLS.

For browser sessions, cookies should normally include Secure, HttpOnly, and an appropriate SameSite attribute. Secure prevents transmission over unencrypted connections. HttpOnly reduces exposure to client-side scripts, particularly in some cross-site scripting scenarios. SameSite limits cross-site transmission and can reduce cross-site request forgery, though it is not a complete CSRF defense. State-changing requests should use an explicit anti-CSRF mechanism where browser cookie authentication is used.

Session fixation occurs when an attacker causes a victim to authenticate using a session identifier known to the attacker. The application must issue a new session identifier after login and after privilege elevation. It should also invalidate the old identifier. Logout should invalidate the server-side session, not merely delete a browser cookie. Password changes, MFA enrollment changes, suspected compromise, and high-risk administrative actions should cause appropriate session revocation or reauthentication.

Idle and absolute timeouts should reflect risk and usability. A long-lived administrative session increases exposure, while an excessively short timeout may cause insecure workarounds. Concurrent-session management, device visibility, notification of unusual login events, and user-controlled revocation can improve security. JWTs do not eliminate these concerns. A JWT that has not expired may remain usable even after a user logs out unless the architecture supports revocation, short lifetimes, token rotation, introspection, or another compensating control.

Mobile and single-page applications require particular care. Long-lived tokens stored in browser local storage are exposed to malicious scripts if an XSS vulnerability exists. More secure designs use authorization-code flows with PKCE, short-lived access tokens, carefully protected refresh tokens, and a backend-for-frontend where appropriate. Tokens should not be placed in URLs because URLs may be stored in browser history, proxies, analytics systems, and referrer data.

Authorization Models and Policy Decisions

Authorization should be deny-by-default: an operation is rejected unless a policy explicitly permits it. The system should validate authorization on every security-sensitive request and on the server side. Hiding a user-interface control is not an authorization mechanism. Object-level authorization is essential; a user permitted to view one invoice must not gain access merely by changing an invoice identifier in a URL.

Role-Based Access Control (RBAC) assigns permissions to roles and roles to subjects. It is understandable and effective where responsibilities are stable, such as analyst, supervisor, or payroll administrator. However, large role inventories can produce role explosion, and role membership alone may not express resource ownership, location, time, risk, or transaction value.

Attribute-Based Access Control (ABAC) evaluates attributes of the subject, resource, action, and environment. A policy might permit a clinician to view a patient record when the clinician is assigned to that patient, is using an approved device, and is operating during an authorized period. ABAC is expressive but requires reliable attribute sources, consistent terminology, policy testing, and explainable decisions.

Policy-Based Access Control is a broader approach in which rules are externalized from application code and evaluated by a policy engine. A common conceptual architecture contains a Policy Administration Point, where policies are authored; a Policy Decision Point, which evaluates requests; and a Policy Enforcement Point, which intercepts actions and enforces decisions. Policy information points supply attributes such as department, device health, or data classification. Separating decision logic from business code improves consistency, but a policy engine becomes a critical dependency and must be highly available, monitored, and governed.

Least privilege grants only the access required for an approved purpose. Separation of duties prevents one person or service from completing an entire high-risk process alone. Just-in-time access grants elevated privileges for a limited period and can be combined with approval, reason capture, and recording. These principles should be applied to administrators, developers, automated workloads, and third-party integrations.

Authorization decisions should be auditable and explainable. Logs should record the subject, action, resource, decision, relevant policy version, and correlation identifier, while avoiding unnecessary sensitive data. Policy testing should include positive, negative, boundary, and conflict cases. Deny rules and exception paths deserve particular attention because an overly broad allow rule can silently override intended restrictions.

OAuth 2.0, OpenID Connect, and Federation

OAuth 2.0 is an authorization framework for delegated access. It allows a resource owner to authorize a client to obtain an access token for a resource server without revealing the resource owner’s password to the client. OAuth is not, by itself, an authentication protocol. OpenID Connect adds an identity layer on top of OAuth 2.0 and provides an ID token describing the authentication event and the subject.

Important OAuth roles are the resource owner, client, authorization server, and resource server. The authorization-code flow is generally preferred for web and native applications. PKCE binds the authorization request to the client’s later code exchange and helps protect against intercepted authorization codes. Public clients, including many mobile applications, cannot safely keep a client secret, so PKCE is particularly important.

An ID token is intended for the client and should not be used as an API access token merely because it is a signed JWT. The client should validate the issuer, audience, signature, expiration, nonce, and relevant time claims. Access tokens should be accepted only by their intended resource server, with scopes and claims checked according to that service’s policy. Redirect URIs must be exact or tightly controlled; open redirectors can undermine authorization-code protections.

Federation allows one domain or organization to rely on identity assertions from another. SAML and OpenID Connect are widely used federation technologies. Federation reduces duplicate accounts and improves centralized lifecycle management, but it creates transitive trust. The relying party must validate issuer, signature, audience, time validity, nonce or state where applicable, and attribute interpretation. Logout, account linking, name changes, and identifier reuse require careful design. A stable, provider-issued subject identifier is safer for account linkage than an email address that may change.

Common protocol failures include accepting unsigned or incorrectly signed tokens, failing to validate audience, confusing access and ID tokens, weak state or nonce validation, permissive redirect URIs, leaking authorization codes, and granting broad scopes. Security libraries and identity-provider guidance reduce implementation risk, but developers remain responsible for configuring them correctly.

A Detailed Illustrative Case: The Overprivileged Claims Portal

Background

A fictional insurance company, Northbridge Assurance, operates a web portal for policyholders, brokers, and claims employees. The portal uses OpenID Connect for login, OAuth access tokens for internal APIs, and RBAC roles such as customer, broker, claims examiner, and administrator.

Situation and Problem

A security review discovers that a broker can alter an invoice identifier in an API request and retrieve another organization’s invoice. The portal also accepts an ID token at an internal API, uses a long-lived browser token, and does not revoke refresh tokens when a user changes a password. Former employees retain access until their tokens expire. The organization believes that use of a reputable identity provider means the portal is secure.

Analysis

The primary failure is broken object-level authorization. Authentication establishes that the caller is a broker, but it does not establish entitlement to every invoice. The API trusts a role claim without checking tenant ownership and resource relationship. The use of an ID token at the API reflects a protocol misunderstanding: the token’s audience and purpose are different. Long-lived tokens increase the impact of theft, while incomplete revocation weakens the leaver process.

Approach and Solution

Northbridge first documents the identity lifecycle and identifies owners for people, service accounts, signing keys, and policies. APIs are changed to accept only access tokens issued for their specific audience. Every invoice request evaluates subject, tenant, resource ownership, action, and transaction status. The authorization-code flow with PKCE is adopted for applicable clients, and redirect URIs are restricted.

Access tokens become short-lived, refresh-token rotation is enabled, and reuse detection revokes the token family. Password changes, account suspension, and employment termination trigger revocation of sessions and delegated grants. The portal uses secure cookies, server-side session invalidation, CSRF protection, and reauthentication for sensitive actions. Authorization decisions and policy versions are logged without recording full financial documents.

Outcome

The corrected design prevents cross-tenant invoice access, reduces the useful lifetime of stolen tokens, and gives security staff evidence for investigating denied and permitted actions. Periodic access reviews identify stale broker accounts, while automated deprovisioning connects the human-resources system to the identity platform.

Learning Points

The case demonstrates that identity-provider integration is not equivalent to application authorization. Tokens require purpose, audience, lifetime, and revocation controls. Authorization must be enforced at the resource boundary, and lifecycle events must reach every credential system that can grant access.

Common Failures, Constraints, and Trade-offs

Identity systems fail when teams treat authentication as a login screen rather than a distributed security service. Frequent mistakes include storing plaintext or fast-hashed passwords, relying on SMS as the only high-risk factor, exposing tokens in URLs or logs, failing to rotate session identifiers, trusting client-supplied roles, omitting tenant checks, accepting tokens without audience validation, and using default-deny rules only in theory.

Usability and security require deliberate balance. Strong MFA can create accessibility barriers; recovery channels can become weaker than primary authentication; short timeouts can encourage unsafe credential reuse; and fine-grained policies can become impossible to administer. Risk-based authentication should not become opaque discrimination. Exceptional access should be documented, time-limited, approved, monitored, and reviewed.

Distributed authorization also introduces availability and consistency concerns. If a policy decision point is unavailable, fail-open behavior may create security exposure, while fail-closed behavior may interrupt essential business operations. Critical systems should define emergency procedures, cached decision limits, policy versioning, and recovery priorities in advance.

Governance, Privacy, and Professional Responsibility

Identity data is personal and often sensitive. Organizations should collect only what is necessary, define retention periods, restrict administrative access, protect audit records, and provide appropriate transparency. Biometric data deserves special care because it cannot be changed like a password. Access decisions should be explainable and should not rely on irrelevant or discriminatory attributes.

Governance should assign accountability for identity proofing, role design, policy approval, key management, incident response, and access review. Regulatory obligations vary by jurisdiction and sector, but principles such as least privilege, traceability, data minimization, segregation of duties, and timely removal of access are broadly relevant. Audit logs must be protected from tampering and should themselves avoid becoming a source of sensitive-data leakage.

Automation, Analytics, and Emerging Developments

Identity platforms increasingly automate provisioning, group membership, credential rotation, policy testing, and anomalous-login detection. Analytics can identify impossible travel, unusual download volume, dormant accounts, privilege escalation, and token use from unexpected environments. Such signals should support investigation rather than produce unquestioned automated denial, particularly where errors could affect employment, healthcare, or access to essential services.

Passkeys based on WebAuthn are becoming an important alternative to password-only authentication because they use public-key cryptography and are resistant to many phishing attacks. Workload identity and short-lived, federated credentials are replacing some static cloud keys. Zero-trust architectures emphasize continuous evaluation of identity, device, resource, and context rather than assuming that network location implies trust.

Policy-as-code enables version control, peer review, automated testing, and deployment pipelines for authorization rules. Artificial intelligence may assist with policy analysis and anomaly detection, but generated policies require human review, formal test cases, traceability, and protection against biased or unsafe recommendations. Automation should strengthen accountability, not obscure who authorized a decision.

Best Practices for Secure Implementation

A robust implementation should adopt the following practices:

  • Define identity, authentication, authorization, and accounting responsibilities separately.
  • Use standards-based identity protocols and well-maintained libraries rather than custom cryptography or token formats.
  • Hash passwords with a modern memory-hard function and protect secrets in a managed vault.
  • Prefer phishing-resistant MFA for privileged and high-impact operations.
  • Rotate session identifiers after authentication and privilege changes; invalidate sessions on logout and compromise.
  • Enforce authorization server-side for every sensitive operation, including object and tenant boundaries.
  • Use deny-by-default, least privilege, separation of duties, and time-limited elevation.
  • Validate token signature, issuer, audience, purpose, lifetime, nonce, and scopes.
  • Use authorization-code flow with PKCE where applicable and protect redirect endpoints.
  • Automate joiner–mover–leaver processes and revoke all relevant credentials during deprovisioning.
  • Test policies with adversarial cases, log decisions responsibly, and review access regularly.

Chapter Summary

Secure identity, session, and access control require an integrated lifecycle rather than an isolated login mechanism. Identity proofing, provisioning, authentication, authorization, monitoring, review, and deprovisioning must be connected. Passwords require memory-hard hashing and robust recovery; secrets and keys require controlled storage, rotation, and purpose limitation. MFA improves assurance, with phishing-resistant authenticators offering the strongest protection against credential phishing.

Sessions are bearer credentials and must be generated securely, protected in transit and storage, rotated after authentication, and revoked when risk changes. RBAC is useful for stable organizational responsibilities, while ABAC and policy-based models express contextual and resource-specific decisions. OAuth 2.0 supports delegated authorization, whereas OpenID Connect provides an identity layer; correct token validation, PKCE, redirect protection, and audience checking are essential. Finally, authorization must be enforced at the resource boundary, supported by lifecycle automation, governance, privacy safeguards, monitoring, and continuous testing.

Key Terms

Identification: A claim about the identity of a subject.

Authentication: Verification of a claimed identity or possession of an authenticator.

Authorization: A decision about whether a subject may perform an action on a resource.

Accounting: Recording security-relevant activity for accountability and investigation.

Identity proofing: Establishing confidence that an identity corresponds to a real subject.

Multifactor authentication: Authentication using two or more independent factor types.

Password hashing: One-way computational transformation used to store password verifiers.

Salt: Unique random value added before password hashing to resist precomputation attacks.

Pepper: Secret server-side value used as an additional password-protection measure.

Session fixation: Attack in which a victim authenticates with an attacker-known session identifier.

CSRF: Attack that causes a browser to submit an unwanted authenticated request.

RBAC: Access control based primarily on roles assigned to subjects.

ABAC: Access control based on subject, resource, action, and environmental attributes.

Policy Decision Point: Component that evaluates an authorization request against policy.

OAuth 2.0: Framework for delegated authorization and access-token issuance.

OpenID Connect: Identity and authentication layer built on OAuth 2.0.

Access token: Credential presented to a resource server to request authorized access.

ID token: OpenID Connect token intended to communicate authentication information to a client.

PKCE: Mechanism binding an authorization-code request to its subsequent exchange.

Federation: Arrangement in which one identity domain relies on assertions from another.

Review Questions

Short Answer Questions

1. Distinguish authentication from authorization and accounting.

2. Why is a unique salt used when hashing passwords?

3. State three important protections for browser session cookies.

4. What problem does PKCE address in OAuth 2.0?

5. Define least privilege and separation of duties.

Long Answer Questions

1. Explain the identity lifecycle from proofing through deprovisioning, including joiner–mover–leaver processes.

2. Compare RBAC, ABAC, and policy-based access control, using suitable application examples.

3. Describe secure session management for a browser application and discuss session fixation, CSRF, timeout, and revocation.

4. Explain the distinction between OAuth 2.0 and OpenID Connect and describe the validation of tokens in a secure architecture.

5. Discuss password, secret, and cryptographic-key management practices for a production software system.

Analytical / Application Questions

1. An API accepts a valid access token but allows a user to change an object identifier and retrieve another tenant’s data. Diagnose the failure and propose controls.

2. A company uses passwords and SMS codes for administrators, but several administrators have suffered targeted phishing attacks. Evaluate the present design and recommend a stronger authentication and recovery strategy.

3. A policy engine becomes unavailable during a critical business process. Analyze the security and availability implications of fail-open and fail-closed behavior, and design an appropriate contingency approach.

22. Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes authentication from authorization?

A. Authentication determines what a subject may access, while authorization verifies identity.

B. Authentication verifies a claimed identity, while authorization evaluates permitted actions.

C. Authentication records activity, while authorization encrypts credentials.

D. Authentication creates audit logs, while authorization provisions accounts.

Correct Answer: B. Authentication verifies a claimed identity, while authorization evaluates permitted actions.

Question 2

A user logs in and retains the same session identifier that existed before login. Which vulnerability is most directly indicated?

A. Token replay through audience confusion

B. Password spraying

C. Session fixation

D. Privilege separation

Correct Answer: C. Session fixation

Question 3

Which design provides the strongest protection against phishing among the following choices?

A. Password plus a second password

B. Password plus a security question

C. Password plus SMS code

D. WebAuthn security key bound to the legitimate origin

Correct Answer: D. WebAuthn security key bound to the legitimate origin

Question 4

Why should an API generally reject an OpenID Connect ID token when used as its access token?

A. ID tokens cannot be digitally signed.

B. ID tokens are intended for the client and may have a different audience and purpose.

C. ID tokens always contain passwords.

D. ID tokens are valid only for database connections.

Correct Answer: B. ID tokens are intended for the client and may have a different audience and purpose.

Question 5

Which authorization model is most naturally suited to a rule requiring a clinician to access a record only when assigned to the patient and using an approved device?

A. ABAC

B. Static ACL with no attributes

C. Password-based access control

D. Unauthenticated access control

Correct Answer: A. ABAC

Question 6

What is the primary security purpose of a unique password salt?

A. It allows passwords to be decrypted during recovery.

B. It prevents the need for password hashing.

C. It makes identical passwords produce identical stored values.

D. It reduces the usefulness of precomputed hash tables and distinguishes identical passwords.

Correct Answer: D. It reduces the usefulness of precomputed hash tables and distinguishes identical passwords.

Question 7

Which OAuth 2.0 practice best protects a public client from authorization-code interception?

A. Using an exact redirect URI and PKCE

B. Placing the authorization code in a permanent URL

C. Using an ID token as a client secret

D. Disabling state validation

Correct Answer: A. Using an exact redirect URI and PKCE

Question 8

A broker can access another customer’s invoice by changing an identifier in a request. What is the principal failure?

A. Insufficient password complexity

B. Broken object-level authorization

C. Weak encryption at rest

D. Improper biometric enrollment

Correct Answer: B. Broken object-level authorization

Question 9

Which action is required when an employee leaves an organization?

A. Disable only the directory password and wait for tokens to expire.

B. Change the employee’s display name.

C. Revoke sessions, refresh tokens, keys, and delegated grants associated with the identity.

D. Move the employee into a general-purpose role.

Correct Answer: C. Revoke sessions, refresh tokens, keys, and delegated grants associated with the identity.

Question 10

What does deny-by-default mean in authorization design?

A. Every request is allowed unless a user interface hides the control.

B. A request is rejected unless an applicable policy explicitly permits it.

C. Only administrators require authorization checks.

D. Authorization is performed only during login.

Correct Answer: B. A request is rejected unless an applicable policy explicitly permits it.

Secure Software Development and Code Analysis
Chapter 7 of 15