I9.4 Authentication, Session, and Access Control Code
Learn how fictional developers verify identity, create and maintain secure sessions, enforce route, object, field, tenant, workflow, privileged, and service authorization, manage account lifecycle, preserve structured evidence, and validate both approved and denied access.
Lesson Progress
Authentication, Session, and Access Control Code
High School Intermediate • I9: Secure Coding Basics • Lesson 4 of 8
Readiness Check
Before You Start
0/5 ready
Professional Hook
A Successful Sign-In Does Not Grant Every Object or Action
A fictional teacher can authenticate correctly, hold a valid session, and still be unauthorized for another teacher’s student record. An administrator can have the right role but still need recent reauthentication and dual approval for an export. A disabled account can still create risk if old sessions remain active. Secure code reevaluates current trust at every important boundary.
Weak decision
“The fictional user is signed in and has the teacher role, so the requested record can be returned.”
Strong decision
“Verify the current account and session, trusted tenant, exact record, assignment, role, requested fields, action, workflow, and any required step-up approval before returning data.”
Objective 1
Explain how fictional authentication, session management, authorization, account lifecycle, recovery, reauthentication, and privileged workflows work together without being treated as the same control.
Objective 2
Distinguish identity claims, factors, devices, sessions, cookies, tokens, roles, permissions, tenants, object relationships, workflow state, and business approval.
Objective 3
Review fictional authentication and authorization code paths for trusted server checks, secure session creation, rotation, expiration, revocation, least privilege, and object-level access control.
Objective 4
Design fictional positive and negative tests for sign-in, recovery, session state, role changes, tenant separation, object ownership, privileged actions, and account disablement.
Objective 5
Create a professional fictional Identity, Session, and Access Control Code Review with findings, owners, validation, monitoring, rollback, evidence gaps, and closure criteria.
Why This Matters
Identity Controls Must Remain Current Throughout the Request
Fictional accounts change roles, devices, risk, projects, tenants, employment state, and recovery status. Protected objects also change ownership, assignment, sensitivity, and workflow state. Secure code cannot rely only on information stored at login. It must evaluate the current identity and current resource relationship before every protected action.
Identity and Session Flow
Eight Stages from Discovery to Revocation
1. Identity discovery
A fictional application identifies which account or identity provider should handle the sign-in attempt.
Required checks
Approved domain or account lookup, tenant, application, identity-provider route, anti-enumeration response, and safe redirect.
Evidence
Request ID, account category, tenant, provider choice, redirect destination, and user-visible result.
Failure mode
The application reveals whether every account exists or accepts unapproved redirect destinations.
2. Credential and factor verification
A fictional identity service evaluates approved factors and account state.
Required checks
Password or primary factor, second factor, account enabled state, factor enrollment, retry control, risk, and recovery restrictions.
Evidence
Sign-in ID, factor category, policy result, device label, account state, failure reason, and timing.
Failure mode
The application treats one weak factor, stale recovery answer, or repeated attempt as sufficient.
3. Session creation
A fictional application creates a new recognized session after successful authentication.
Required checks
Fresh identifier, secure cookie attributes, issue time, idle and maximum lifetime, device context, account, tenant, and application scope.
Evidence
Session ID category, account, device, issue and expiry times, cookie metadata, and policy version.
Failure mode
The application keeps a pre-authentication identifier or creates a broad, long-lived, script-readable session.
4. Request recognition
A fictional server connects each request to current session and account state.
Required checks
Session signature or lookup, expiration, revocation, account enabled state, device or risk changes, application scope, and token audience.
Evidence
Request ID, session ID, account ID, device ID, validation result, revocation state, and reason.
Failure mode
The application trusts client claims without checking current session and account state.
5. Authorization
A fictional server decides whether the account may perform the requested action on the exact object and tenant.
Required checks
Role, permission, tenant, ownership, assignment, object state, action, workflow state, field scope, and policy.
Evidence
Account, role, tenant, object, action, policy, decision, reason, and downstream result.
Failure mode
The application checks only that the user is signed in or that the page link was visible.
6. Privileged action
A fictional high-impact workflow requires stronger proof and clearer user intent.
Required checks
Privileged role, recent authentication, step-up factor, exact object, confirmation, approval, idempotency, and enhanced logging.
Evidence
Session age, reauthentication event, approvals, transaction ID, business record, and audit event.
Failure mode
An old ordinary session can change roles, export data, approve payment, or recover another account.
7. Session maintenance
A fictional application updates trust after password changes, role changes, risk events, device changes, and inactivity.
Required checks
Rotation, renewal, idle timeout, maximum lifetime, role refresh, risk review, device state, and token refresh rules.
Evidence
Old and new session IDs, reason, account state, role version, device status, and renewal result.
Failure mode
Old sessions preserve outdated privileges or remain active after important trust changes.
8. Logout, revocation, and account closure
A fictional system ends access when the user logs out or the identity should no longer be trusted.
Required checks
Server-side invalidation, cookie clearing, token revocation where supported, account disablement, device removal, audit logging, and confirmation.
Evidence
Logout event, revoked session inventory, account state, token status, access denial, and owner review.
Failure mode
Only the browser cookie is removed while server-side sessions or other devices remain active.
Authorization Layers
Eight Separate Access Decisions
Route authorization
May the fictional identity reach this function or endpoint at all?
Trusted data
Current account, role, tenant, application, route policy, and session state.
Weak pattern
Hide the route link in the browser or check only a client-supplied role.
Strong pattern
Enforce server-side route policy before protected processing begins.
Object authorization
May the fictional identity access this exact record, file, user, report, or transaction?
Trusted data
Server-resolved object, tenant, owner, assignment, relationship, role, and action.
Weak pattern
Trust a valid-looking identifier or assume role membership grants every object.
Strong pattern
Resolve the object under the current tenant and evaluate the exact relationship and action.
Field authorization
Which fictional fields may this identity view or change inside the approved object?
Trusted data
Role, relationship, data classification, workflow state, and response or update policy.
Weak pattern
Return the full object and hide fields only in the browser.
Strong pattern
Select and return only approved fields on the server.
Action authorization
May the fictional identity perform this read, update, delete, approve, export, invite, or role-change action?
Trusted data
Permission, object state, workflow state, business rule, recent authentication, and approvals.
Weak pattern
Assume access to the object allows every action.
Strong pattern
Evaluate each action independently and record the decision.
Tenant authorization
Does the fictional object and action belong to the same approved tenant or organizational boundary as the identity?
Trusted data
Trusted tenant from the session, server-resolved object tenant, and service scope.
Weak pattern
Use a tenant identifier directly from the request without verification.
Strong pattern
Derive tenant from trusted session and object data, then require an exact match.
Workflow authorization
Is the fictional action allowed at the current step and state of the business process?
Trusted data
Current workflow state, previous approvals, ownership, timing, transaction status, and business rule.
Weak pattern
Allow a later action simply because the user knows the route.
Strong pattern
Require the expected state transition and reject out-of-order or repeated actions.
Privileged authorization
Does the fictional high-impact action require fresh verification, dual approval, or a specialized administrative role?
Trusted data
Privileged role, session age, step-up result, approval record, object, and exact requested change.
Weak pattern
Use the same ordinary session rule for role changes, exports, recovery, and payment approvals.
Strong pattern
Require narrowly scoped privileged authority and fresh verification.
Service authorization
May the fictional application service call the downstream service and perform this operation?
Trusted data
Named service identity, audience, scope, environment, network path, and operation policy.
Weak pattern
Use one shared overprivileged credential for every service.
Strong pattern
Use separate least-privileged service identities with exact scopes and monitoring.
Core Concept
Use the Identity–Session–Object–Action–Evidence Chain
Identity
Which fictional account or service is recognized, and how was it verified?
Session
Is the fictional session current, unexpired, unrevoked, correctly scoped, and aligned with current account state?
Tenant and object
Which fictional tenant and exact record, file, account, report, or transaction is involved?
Action
Which fictional read, update, export, role change, approval, recovery, or configuration action is requested?
Policy
Which fictional role, relationship, workflow, reauthentication, approval, and least-privilege rules apply?
Evidence
Which fictional decision, database, transaction, browser, lifecycle, monitoring, and owner records prove the result?
Session Security
Eight Controls for Current Trust
Fresh identifier at authentication
Replace fictional pre-authentication state with a new session after identity verification.
Risk
A preexisting identifier can remain associated with the authenticated account.
Validation
Confirm the identifier changes at sign-in and the old identifier is not accepted.
Owner: Identity and Application Teams
Secure cookie attributes
Limit fictional browser transport and script access while applying appropriate cross-site behavior.
Risk
Weak attributes can broaden session exposure or send state in unintended contexts.
Validation
Confirm Secure, HttpOnly, appropriate SameSite, narrow host and path, and approved lifetime.
Owner: Application Team
Idle and maximum lifetime
End fictional sessions after inactivity and after an absolute approved period.
Risk
Long-lived forgotten sessions increase exposure after device loss or account misuse.
Validation
Test activity, inactivity, maximum age, renewal, and denied expired requests.
Owner: Identity and Application Teams
Rotation after trust changes
Replace fictional session state after recovery, password change, privilege elevation, or risk decision.
Risk
Old identifiers can preserve trust from before the important change.
Validation
Confirm old identifiers fail and new state reflects the current role and risk.
Owner: Identity Team
Server-side revocation
Invalidate fictional sessions after logout, disablement, security concern, or administrative action.
Risk
Clearing only the browser cookie leaves server-recognized state active.
Validation
Confirm revoked sessions fail on every device and application path.
Owner: Identity and Platform Teams
Session inventory
Allow fictional users and defenders to see active devices, issue times, locations or labels, and recent use where appropriate.
Risk
Unknown sessions can remain unnoticed and difficult to revoke.
Validation
Confirm inventory accuracy, privacy, ownership, and per-session revocation.
Owner: Identity Team
Privilege freshness
Require fictional current role and permission evaluation rather than preserving stale authorization in the session.
Risk
A removed role can remain effective until a long session expires.
Validation
Change a role in the test environment and confirm old access stops according to policy.
Owner: Identity and Application Teams
Safe logout and recovery
End fictional access predictably and avoid creating a weaker alternate path through recovery.
Risk
Recovery or logout gaps can leave sessions active or allow account takeover through weaker evidence.
Validation
Test logout, all-session revocation, recovery verification, old-session denial, and notification.
Owner: Identity Team
Account Lifecycle
Eight Stages from Provisioning to Deletion
Provision
Secure pattern
Create fictional accounts from an approved authoritative source with named owner, tenant, role, and start date.
Risk
Manual or duplicate accounts can be created without clear ownership or purpose.
Evidence
Provisioning request, authoritative record, account ID, owner, role, tenant, and approval.
Activate
Secure pattern
Require fictional initial verification, factor enrollment, secure recovery setup, and policy acceptance.
Risk
Default credentials or incomplete factor setup can leave weak access.
Evidence
Activation event, factor enrollment, recovery method, device, and owner confirmation.
Assign access
Secure pattern
Grant fictional roles and permissions from documented job, project, tenant, and business need.
Risk
Broad default roles or copied access can exceed the actual need.
Evidence
Role request, manager or owner approval, policy decision, and effective permissions.
Review
Secure pattern
Review fictional active accounts, roles, privileged access, service identities, stale sessions, and exceptions on schedule.
Risk
Access remains after job, project, tenant, or responsibility changes.
Evidence
Review campaign, owner decision, removed access, exception, and completion report.
Change
Secure pattern
Update fictional roles, tenant, manager, project, or privilege through approved change and session refresh.
Risk
Old permissions remain active or new access is granted without removing outdated access.
Evidence
Change request, before and after roles, session rotation, tests, and owner approval.
Suspend
Secure pattern
Temporarily prevent fictional sign-in and revoke sessions while preserving required evidence and business records.
Risk
Suspended accounts may retain API tokens, sessions, or service access.
Evidence
Suspension event, revoked sessions, token status, device state, and denial tests.
Disable
Secure pattern
Disable fictional access promptly after separation, confirmed misuse, or end of business need.
Risk
Dormant accounts become forgotten entry points.
Evidence
Authoritative end event, account state, revoked sessions, removed roles, and owner confirmation.
Delete or archive
Secure pattern
Remove fictional account access and personal data according to retention while preserving required audit relationships.
Risk
Deleting the account too early can break evidence, while keeping it indefinitely increases privacy and access risk.
Evidence
Retention decision, archive mapping, deletion record, access test, and owner sign-off.
Code Review
Eight Questions for Identity and Access Code
Trusted identity source
Does the fictional code use server-validated identity and session context rather than client-supplied account, role, or tenant values?
Evidence
Identity middleware, session lookup, claim validation, route context, and negative test.
Warning
Role or tenant is read directly from a form, URL, local storage, or unsigned client data.
Central authorization
Do fictional routes call a shared policy or service that evaluates role, tenant, object, action, and state consistently?
Evidence
Authorization function, policy mapping, route coverage, decisions, and regression tests.
Warning
Each route implements different ad hoc checks or trusts browser visibility.
Object resolution
Does the fictional server resolve the protected object under the trusted tenant before making an access decision?
Evidence
Object service, tenant filter, ownership or assignment record, and wrong-object tests.
Warning
The code loads an object by client-provided ID without tenant or relationship checks.
Session state
Does the fictional code verify expiration, revocation, account state, device or risk policy, and current role on protected requests?
Evidence
Session middleware, revocation lookup, account state, role version, and denial tests.
Warning
A signed or stored session is accepted without current-state checks.
Privileged action
Does the fictional code require recent authentication, exact privileged role, confirmation, approval, and idempotency where needed?
Evidence
Step-up event, approval record, transaction ID, route decision, and duplicate-request test.
Warning
An ordinary old session can complete the high-impact action.
Recovery and role change
Does fictional recovery or access change trigger session revocation, notification, audit logging, and renewed policy evaluation?
Evidence
Recovery event, old-session denial, role-change record, notification, and audit result.
Warning
Recovery is weaker than sign-in or old sessions retain previous trust.
Error behavior
Do fictional authentication and authorization errors remain safe while preserving useful structured evidence?
Evidence
User response, internal decision reason, request ID, event fields, and privacy review.
Warning
The response reveals account existence, role details, object presence, or internal policy structure unnecessarily.
Monitoring and ownership
Are fictional sign-in, recovery, session, authorization, privilege, account, and service-identity events monitored by accountable owners?
Evidence
Source inventory, alert routes, owner, retention, access review, and health test.
Warning
Critical decisions exist only in local logs or have no owner and retention.
Defensive Workflow
Review Identity, Sessions, and Access in Six Steps
Map identity and trust
Identify fictional accounts, factors, devices, identity providers, applications, sessions, tenants, roles, and authoritative sources.
Trace session state
Review fictional creation, cookie or token attributes, rotation, renewal, idle and maximum lifetime, revocation, logout, and recovery.
Map authorization
Evaluate fictional route, object, field, action, tenant, workflow, privileged, and service authorization.
Review code and policy
Confirm fictional trusted context, central policies, object resolution, current-state checks, safe errors, and structured events.
Test both access and denial
Run fictional positive, wrong-role, wrong-tenant, wrong-object, expired, revoked, stale-role, duplicate, and recovery tests.
Monitor and close
Validate fictional account lifecycle, session inventories, access reviews, alerts, business outcomes, rollback, residual risk, and owner approval.
Correlated Identity Timeline
Follow a Fictional Teacher Account from Provisioning to Access Review
08:00:00
Provisioning
A fictional teacher account is created from an approved employment record with teacher role and Meadowbrook tenant.
The account has an authoritative source, owner, role, and tenant.
08:05:00
Activation
The fictional teacher completes initial verification, enrolls an authenticator, and configures approved recovery.
The account becomes active under the identity policy.
09:12:00
Sign-in
The teacher completes password and authenticator verification from a known managed device.
Approved authentication and device context are established.
09:12:01
Session
The application creates a new Secure, HttpOnly, SameSite=Lax session with approved idle and maximum lifetime.
A protected post-authentication session is issued.
09:14:00
Record request
The fictional teacher requests a student-support record assigned to another teacher.
A protected object access decision is required.
09:14:01
Route code
The route checks authentication and teacher role but does not verify the assignment relationship.
The route and role controls are incomplete for object access.
09:14:02
Database
The unassigned record is returned in the supplied safe test environment.
A test-environment object-authorization impact is confirmed.
09:18:00
Containment
The affected route is blocked from release and the test session is revoked.
Narrow containment prevents deployment and ends the reviewed session.
09:30:00
Remediation
A central policy resolves tenant, record, assignment, role, action, field scope, and session state using trusted server data.
Authorization now matches the protected object and workflow.
09:45:00
Positive test
The teacher successfully views an assigned record and only approved fields.
Legitimate use remains available.
09:48:00
Negative test
Unassigned, wrong-tenant, wrong-role, missing-session, expired-session, and revoked-session requests are denied.
Several identity, session, and authorization failure cases are controlled.
10:00:00
Role change
The fictional teacher role is removed in the test identity system and existing sessions are refreshed or revoked according to policy.
Current role state replaces stale privilege.
10:05:00
Role test
The old session cannot access teacher routes after the role change.
Stale authorization is not preserved.
Day 7
Monitoring
No unexplained cross-tenant or unassigned-record results appear and session source health remains normal.
Short-term operational evidence supports the controls.
Day 30
Access review
The account owner confirms the teacher role, active sessions, recovery method, and application access remain appropriate.
Lifecycle review maintains least privilege over time.
Key Vocabulary
Identity, Session, and Access Control Terms
Authentication
A fictional process that evaluates an identity claim using approved evidence such as a password, authenticator, device, or recovery method.
Authorization
A fictional server-side decision about whether a recognized identity may perform a specific action on a specific object in a specific tenant and workflow state.
Session
A fictional server-recognized period that connects an authenticated account with current trust, device, risk, role, and application state.
Session rotation
A fictional process that replaces a session identifier after sign-in, recovery, privilege elevation, or another trust change.
Session revocation
A fictional process that invalidates one or more active sessions after logout, account disablement, recovery, security concern, or administrative action.
Reauthentication
A fictional requirement for fresh identity verification before a high-impact action such as export, role change, recovery, or payment approval.
Object authorization
A fictional server-side check that confirms the identity may access the exact requested record, file, account, project, or transaction.
Tenant isolation
A fictional control that prevents identities and services from accessing data or actions belonging to another organization or logical boundary.
Least privilege
A fictional principle that grants only the permissions required for the approved role, object, workflow, and time period.
Step-up verification
A fictional stronger verification requirement triggered by increased risk, privilege, sensitivity, or business impact.
Account lifecycle
The fictional creation, activation, role assignment, review, suspension, disablement, recovery, and deletion of an identity.
Access decision
A fictional structured result that records the identity, session, role, tenant, object, action, policy, reason, and outcome.
Fake Dashboard
Fake Identity and Access Code Review Dashboard
Training dashboard for the fictional Meadowbrook student-support applications.
Protected routes
84
Fictional record, reporting, messaging, file, account, recovery, administration, and configuration routes.
Central-policy coverage
77
Routes using approved identity, session, tenant, object, action, and workflow authorization.
Open findings
7
Object relationship, field filtering, stale role, recovery, privileged reauthentication, service scope, and logout cases.
Fake SOC Alert
Object Authorization Missing from Teacher Record Route
Source: Fake Identity and Access Review Console • Time: 09:14 AM
Fake Log Panel
Fake Identity, Session, and Authorization Timeline
08:00:00 PROVISION account='teacher-204' source='employment_record' tenant='meadowbrook' 08:05:00 ACTIVATE factor='authenticator' recovery='approved' 09:12:00 SIGN_IN account='teacher-204' factor1='pass' factor2='pass' device='managed-17' 09:12:01 SESSION_CREATE secure='true' http_only='true' same_site='Lax' 09:14:00 REQUEST route='/support/record' object='record-884' 09:14:01 ROUTE_CHECK authenticated='true' role='teacher' assignment_check='missing' 09:14:02 DATABASE unassigned_record='returned' 09:18:00 CONTAIN route='blocked_from_release' session='revoked' 09:30:00 REMEDIATE tenant='verified' assignment='verified' object='verified' fields='filtered' 09:45:00 POSITIVE_TEST assigned_record='pass' 09:48:00 NEGATIVE_TEST unassigned='deny' wrong_tenant='deny' wrong_role='deny' expired='deny' revoked='deny' 10:00:00 ROLE_CHANGE teacher_role='removed' sessions='refresh_or_revoke' 10:05:00 ROLE_TEST old_session_teacher_access='deny' DAY7 MONITOR cross_tenant_results='0' source_health='normal' DAY30 ACCESS_REVIEW role='confirmed' sessions='reviewed' recovery='reviewed'
Training note: this is fake data for defensive analysis practice only.
Analyze the Evidence
Which Identity and Access Conclusion Is Best Supported?
Which conclusion is strongest?
Common Mistakes
Mistakes That Weaken Identity and Access Code
Safe Practice Lab
Complete a Fictional Identity, Session, and Access Code Review
Fictional Evidence Set
Meadowbrook Identity and Access Review
Review forty-four supplied fictional records covering provisioning, activation, sign-in, factors, sessions, cookies, rotation, expiration, revocation, roles, tenants, objects, fields, workflow, recovery, privileged actions, service identities, code review, tests, monitoring, and access review.
Required Analysis
- Map fictional accounts, factors, devices, identity providers, applications, sessions, tenants, roles, and authoritative sources.
- Trace session creation, attributes, rotation, idle and maximum lifetime, renewal, revocation, logout, and recovery.
- Review route, object, field, action, tenant, workflow, privileged, and service authorization.
- Inspect trusted identity sources, central policies, object resolution, current-state checks, safe errors, and structured events.
- Design positive and wrong-role, wrong-tenant, wrong-object, expired, revoked, stale-role, duplicate, and recovery tests.
- Document findings, owners, remediation, monitoring, rollback, evidence gaps, residual risk, and closure criteria.
Scenario Decision Lab
A Route Uses a Client-Supplied Role
A fictional administrative route reads a role value from browser state and allows the page when the value says administrator.
Scenario Decision Lab
A Password Change Leaves Old Sessions Active
A fictional account changes its password after a security concern, but sessions on two other devices remain recognized.
Defender Habits
Authentication, Session, and Access Control Code Checklist
Check Your Understanding
I9.4 Mini Quiz: Authentication, Session, and Access Control Code
Choose your answers first. Explanations appear only after submission.
1. Which statement correctly separates fictional authentication and authorization?
2. Why should a fictional session rotate after sign-in or privilege elevation?
3. Which object-authorization design is strongest?
4. What should fictional logout do?
5. Why should high-impact fictional actions require reauthentication?
6. What should happen after a fictional role is removed?
7. Which closure plan is strongest after a fictional identity and authorization finding?
Portfolio Prompt
Portfolio Prompt
Create a fictional Identity, Session, and Access Control Code Review using at least forty-four provisioning, activation, sign-in, factor, device, session, cookie, rotation, expiration, revocation, role, tenant, object, field, workflow, recovery, privileged-action, service-identity, code-review, test, monitoring, and access-review records. Include an identity-flow map, session-control matrix, authorization coverage map, account-lifecycle review, findings, owners, positive tests, negative tests, rollback, evidence gaps, residual risk, and closure criteria.
Key Takeaways
What You Should Remember
Navigation