Backend Development

Chapter 8
Authentication, Authorization, and Backend Security

Certificate in Full stack programming
Backend Development   •   Certificate

Authentication, Authorization, and Backend Security

Introduction

Backend security protects the confidentiality, integrity, and availability of applications, data, and services. In a full-stack system, the backend is particularly important because it receives untrusted input, accesses databases, applies business rules, and often integrates with payment, identity, messaging, and cloud services. A visually secure user interface cannot compensate for an insecure API: attackers can call backend endpoints directly.

This chapter distinguishes two closely related ideas. Authentication establishes who a requester is. Authorization determines what that requester may do. Security also requires secure credential storage, robust session or token management, validation, protection against common attacks, careful error handling, and operational control of secrets.

Security is not a single library or configuration setting. It is a lifecycle practice involving threat modeling, secure design, defensive implementation, testing, monitoring, incident response, and periodic review. The principles of least privilege, defense in depth, secure defaults, fail-safe behavior, and separation of duties provide a useful foundation.

Learning Objectives

By the end of this chapter, a learner should be able to:

  1. Explain authentication, authorization, identity, sessions, cookies, and tokens.
  2. Store passwords using modern adaptive password-hashing algorithms.
  3. Implement secure session-based and token-based authentication.
  4. Apply role-based and permission-based access control on the server.
  5. Describe OAuth 2.0 and OpenID Connect at a conceptual level.
  6. Validate input safely and mitigate injection, broken access control, data exposure, CSRF, SSRF, and related OWASP risks.
  7. Manage secrets, logs, errors, dependencies, and security configuration responsibly.
  8. Evaluate security trade-offs in a realistic backend application.

1. Identity, Authentication, and Authorization

An identity is a representation of an entity, such as a user, service, device, or organization. Authentication verifies a claimed identity. Common authentication factors are:

  • Something the user knows: a password or PIN.
  • Something the user has: a hardware key or authenticator device.
  • Something the user is: a biometric characteristic.
  • A contextual factor: location, device posture, or network condition.

A password alone is a single-factor mechanism. Multi-factor authentication (MFA) combines independent factors. A password and a one-time code generated by the same password manager are not necessarily independent factors; designers should evaluate the actual threat model.

Authorization is the enforcement of permitted actions after authentication. For example, authentication may establish that the requester is Alice, while authorization determines whether Alice may view an invoice, edit a course, or delete an account. Authorization must be enforced on the backend for every protected operation, not merely hidden in the interface.

A useful request-processing sequence is:

  1. Parse the request safely.
  2. Authenticate the requester when authentication is required.
  3. Load the relevant resource and its security context.
  4. Authorize the requested action using server-side rules.
  5. Validate business constraints.
  6. Perform the operation with least-privilege database and service credentials.
  7. Return only the necessary response data and record appropriate security events.

Authentication and authorization are different failure domains. A valid user may still be unauthorized to access another user’s object. Conversely, a correct authorization rule cannot help if an attacker can impersonate a privileged account.

2. Password Security

Passwords should not be stored in plaintext and should not be encrypted for routine password verification. Encryption is reversible when a key is available; password storage should instead use a one-way, deliberately expensive password-hashing function.

A password hash record normally contains the algorithm, cost parameters, a unique salt, and the resulting hash. A salt is public random data that ensures equal passwords produce different records and prevents effective use of precomputed rainbow tables. A salt is not a secret and does not replace a strong password-hashing function.

Suitable password-hashing approaches include Argon2id, scrypt, and bcrypt, subject to current library guidance and organizational policy. Argon2id is commonly preferred for new systems because it can impose memory as well as time costs. A password-hashing cost should be calibrated on the production class of hardware so that verification is expensive for attackers but acceptable for legitimate users. The cost must be reviewed as hardware changes.

The verification process is:

  1. Retrieve the account’s stored hash record.
  2. Extract its algorithm and parameters.
  3. Hash the supplied password using the stored salt and parameters.
  4. Compare the result using the password library’s verification function.
  5. Return a generic failure message if verification fails.

A server should never log passwords, password-reset links, authentication headers, or session identifiers. Password policies should encourage long passwords or passphrases, reject known-compromised passwords where feasible, rate-limit attempts, and support password managers. Forced periodic changes without evidence of compromise can encourage predictable modifications and are not a substitute for MFA.

Password-reset tokens should be random, single-use, short-lived, and stored in a form that does not expose the usable token if the database is leaked. After a successful reset, existing sessions should normally be invalidated or re-evaluated. Account-enumeration risks can be reduced by using similar response messages and timing for existing and non-existing accounts, while still providing accessible user guidance.

3. Sessions, Cookies, and Tokens

3.1 Server-side sessions

In a session architecture, the browser receives a random session identifier. The server stores the session state, such as the user identifier, authentication time, and security-relevant metadata. The browser sends the identifier on subsequent requests.

A session identifier must be generated with a cryptographically secure random generator, have sufficient entropy, and be meaningless without server-side state. On login, the identifier must be regenerated to prevent session fixation. Sessions should have idle and absolute expiration limits, and logout should revoke the server-side session.

A browser cookie carrying a session identifier should normally use:

  • Secure, so it is sent only over HTTPS.
  • HttpOnly, so ordinary client-side scripts cannot read it.
  • SameSite, such as Lax or Strict where compatible, to reduce cross-site request risks.
  • An appropriate narrow Domain and Path.

Cookies do not make an application automatically secure. Cross-site request forgery (CSRF) remains possible depending on cookie policy and application behavior.

3.2 Tokens

A bearer token grants access to whoever possesses it. Therefore, exposure through logs, browser storage, referrer data, screenshots, malicious extensions, or a compromised device may be equivalent to credential theft. Access tokens should be short-lived and transmitted only over TLS.

A JSON Web Token (JWT) is a token format, not a complete authentication system. A signed JWT can provide integrity and claims, but signing does not automatically provide confidentiality. Sensitive information should not be placed in ordinary readable JWT payloads. The server must explicitly restrict accepted algorithms, verify the signature, issuer, audience, expiration, and relevant claims, and reject malformed or unexpected tokens.

JWT revocation is more complex than server-side session revocation. Common approaches include short access-token lifetimes, refresh-token rotation, server-side refresh-token records, token-family revocation, and an emergency deny-list for high-risk events. Refresh tokens require especially careful storage and rotation.

The choice between sessions and tokens depends on architecture. Traditional browser applications often benefit from secure server-side sessions. Distributed APIs may use tokens, but opaque reference tokens with server-side introspection can make revocation and privacy easier. “Stateless” does not eliminate the need for key management, expiry, revocation strategy, or authorization checks.

3.3 Session and token comparison

ConcernServer-side sessionSigned access token
Primary stateStored on serverIncluded in token claims
RevocationUsually straightforwardRequires expiry, rotation, or deny-list design
Browser deliveryCommonly secure cookieCookie or authorization header
ScalingRequires shared store or routing strategyEasier distribution, but key and claim management remain
Main riskSession theft and fixationToken theft, claim misuse, key errors

4. Authorization Models

Role-based access control (RBAC) assigns permissions to roles and roles to users. A user may have roles such as learner, instructor, or administrator. RBAC is easy to explain and works well when organizational responsibilities are stable.

Permission-based access control assigns fine-grained capabilities, such as course.read, course.edit, or user.suspend. It can express least privilege more precisely than broad roles. In practice, roles often act as bundles of permissions.

Attribute-based access control (ABAC) evaluates attributes of the subject, resource, action, and environment. A rule might allow an instructor to edit a course only when the instructor owns it and the course is in a draft state. ABAC is expressive but requires disciplined policy design and testing.

Authorization should be deny-by-default. A route should explicitly state which action is being requested and which policy permits it. Developers must avoid insecure direct object references, in which changing /orders/1001 to /orders/1002 reveals another customer’s order. The backend should query the object with an ownership or permission condition, rather than loading it solely by an identifier and checking later.

For administrative actions, require stronger controls such as MFA, recent authentication, explicit confirmation, audit logging, and separation of duties. Do not trust role or price information supplied by the client. The server must derive security-sensitive values from trusted data and policies.

5. OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorization framework that enables a client to obtain limited access to a resource on behalf of a resource owner. It does not, by itself, define user authentication. OpenID Connect (OIDC) adds an identity layer on top of OAuth 2.0 and provides an ID token describing an authenticated subject.

In a typical authorization-code flow with Proof Key for Code Exchange (PKCE):

  1. The client creates a random code verifier and a derived challenge.
  2. The client redirects the user to the authorization server.
  3. The authorization server authenticates the user and obtains consent where appropriate.
  4. The server redirects back with a short-lived authorization code.
  5. The client exchanges the code and verifier for tokens.
  6. The client validates the returned tokens and establishes its local session.

The redirect URI must be pre-registered and matched exactly according to provider rules. The state parameter helps prevent request-forgery and login-CSRF attacks. PKCE protects the authorization code if it is intercepted. Clients must validate issuer, audience, nonce where applicable, signature, expiration, and token type. A backend should not accept an arbitrary access token merely because it has a familiar shape.

OAuth scopes should be narrow and consent should be meaningful. A provider’s access token is intended for the provider’s APIs, not automatically for the application’s own API. When using social login, the application should map a stable provider subject identifier to a local account and should carefully handle account linking.

6. Secure Input Validation and Output Handling

Validation establishes that input conforms to the application’s expected type, structure, length, range, and business rules. It should occur at the trust boundary and again where assumptions change. Use allowlists where practical: for example, accept a known enumeration of sort fields rather than passing an arbitrary field name to a database query.

Validation is not the same as sanitization. Sanitization modifies data for a particular output context; validation rejects unacceptable input. Output encoding must be context-specific. HTML, JavaScript, URL, SQL, shell, and log contexts have different escaping requirements.

Database injection is prevented primarily through parameterized queries or a correctly used query builder/ORM. A parameterized query treats supplied values as data rather than SQL syntax. Avoid constructing SQL, shell commands, LDAP filters, or document queries by concatenating untrusted strings. Stored procedures are not automatically safe if they construct dynamic commands internally.

For file uploads, validate size, type, content signature, and storage location. Rename files server-side, store them outside executable web roots, scan where appropriate, and prevent path traversal. Do not trust a filename extension or browser-provided MIME type.

Error responses should help legitimate clients without disclosing stack traces, SQL statements, internal hostnames, secrets, or personal data. Detailed diagnostics belong in access-controlled logs, with correlation identifiers that do not expose credentials.

7. Common Backend Threats and Defenses

Broken access control

Broken access control includes missing authorization, horizontal privilege escalation between users, vertical escalation to administrator functions, and insecure object references. Mitigations include centralized policy checks, resource ownership conditions, deny-by-default routing, authorization tests for every sensitive endpoint, and review of background jobs and administrative APIs.

Data exposure and cryptographic failures

Collect only necessary data, classify it, encrypt sensitive data in transit, and protect data at rest according to risk. TLS certificate validation must not be disabled in production. Encryption keys must be separate from encrypted data and managed through a controlled key-management system. Hashing, encryption, encoding, and tokenization are different techniques and should not be treated as interchangeable.

Responses should use data-transfer objects or explicit field selection rather than serializing entire database entities. This prevents accidental exposure of password hashes, internal flags, reset tokens, or sensitive profile fields.

Cross-site request forgery

CSRF exploits a browser’s automatic credential submission, especially cookies. Defenses include SameSite cookies, synchronizer tokens, and, where suitable, the double-submit-cookie pattern. State-changing operations should use methods such as POST, PUT, PATCH, or DELETE rather than GET, but the method alone is not a CSRF defense. Validate an appropriate origin or referer signal where feasible, and never rely solely on a custom header if the client can be induced to send it.

Server-side request forgery

SSRF occurs when a server fetches an attacker-influenced URL and can reach internal services, cloud metadata endpoints, or restricted networks. Prefer a fixed set of outbound destinations. If arbitrary URLs are necessary, parse them with a trusted URL library, allowlist schemes and hosts, resolve DNS carefully, block private and link-local address ranges, restrict redirects, set timeouts and response-size limits, and isolate the fetcher’s network privileges. SSRF defenses require both application checks and network controls because DNS rebinding and redirect behavior can defeat simplistic filters.

Other frequent risks

  • Security misconfiguration: remove development endpoints, change default credentials, use secure headers, and maintain production configuration baselines.
  • Vulnerable components: inventory dependencies, use lockfiles, update promptly, monitor advisories, and remove unused packages.
  • Insecure deserialization: avoid deserializing untrusted objects; use constrained formats and explicit schemas.
  • Resource exhaustion: impose request, upload, query, and concurrency limits; use queues and cancellation.
  • Clickjacking and content injection: use appropriate browser security headers, output encoding, and a carefully designed Content Security Policy.
  • Logging failures: record authentication failures, privilege changes, token events, and sensitive administrative actions without recording secrets or unnecessary personal data.

OWASP Top 10 categories are useful awareness guidance, but they are not a complete security standard. Teams should supplement them with threat modeling, secure coding standards, architecture review, penetration testing, dependency management, and incident exercises.

8. Secrets Management and Operational Security

Secrets include database passwords, signing keys, API keys, encryption keys, and service credentials. They should not be committed to source control, embedded in frontend bundles, placed in container images, or copied into issue tickets. Environment variables can be useful for injection at deployment time, but they are not automatically a complete secrets-management solution.

A secrets manager should provide controlled storage, access policies, audit trails, rotation, and—where possible—short-lived credentials. Applications should receive only the secrets they need. Separate development, test, and production secrets. If a secret may have been exposed, rotate it immediately, investigate access, and remove it from future history; deleting a file from the latest commit does not remove it from repository history or logs.

Signing-key rotation requires a planned overlap period: services must be able to validate tokens signed with an old key while new tokens use the new key, followed by retirement of the old key after applicable tokens expire or are revoked. Key identifiers and a trusted key-distribution process support this transition.

Security logs should be centralized, access-controlled, time-synchronized, and protected from tampering. Alerting should focus on meaningful signals such as repeated failures, unusual privilege changes, impossible travel patterns, mass downloads, or access to sensitive administrative routes. Monitoring must respect privacy and retention requirements.

9. Illustrative Case: Course Management API

Background

An educational platform provides a REST API for learners, instructors, and administrators. It uses browser sessions, a relational database, uploaded assignment files, and an external identity provider for optional institutional login.

Problem

An initial implementation hides instructor screens from learners but exposes GET /api/courses/{id} and DELETE /api/users/{id} without consistent server-side checks. Passwords are hashed with a fast general-purpose hash, reset tokens are logged, and an assignment-preview endpoint fetches a URL supplied by the user.

Analysis

The interface is being mistaken for authorization. The course endpoint is vulnerable to horizontal access violations, while the user endpoint permits vertical privilege escalation. Fast hashing is unsuitable for password resistance. Reset-token logging creates a credential-equivalent secret in log storage. The preview endpoint creates an SSRF path to internal services.

Approach and solution

The team introduces a centralized authorization policy. A learner may read only published courses and their own submissions. An instructor may manage courses assigned to that instructor. An administrator may manage users, but destructive operations require recent MFA and an audit event. Resource queries include ownership and publication predicates rather than relying on post-query checks.

Passwords are migrated to Argon2id on successful login, with a controlled reset for inactive accounts. Reset tokens are random, single-use, short-lived, stored as hashes, and excluded from logs. Browser sessions use Secure, HttpOnly, and appropriate SameSite cookies; session identifiers are rotated after login.

The preview feature is changed to accept only stored assignment references rather than arbitrary URLs. Where external retrieval is genuinely required, a separate restricted worker uses an outbound allowlist, DNS and IP checks, redirect limits, timeouts, and size limits. Database operations use parameterized queries, and response schemas exclude internal fields.

Outcome

The platform now tests authorization for each role and ownership combination, scans dependencies, monitors unusual administrative activity, and runs security checks in CI. The design does not eliminate all risk, but it removes several direct exploit paths and makes security assumptions explicit and testable.

Learning points

The case demonstrates that secure authentication does not provide secure authorization, that secrets can leak through operational systems, and that SSRF is a system-design problem rather than merely a URL-validation problem. It also shows the value of defense in depth: policy checks, safe libraries, network isolation, logging controls, and tests reinforce one another.

10. Security Testing and Professional Practice

Security testing should begin during design. A simple threat-modeling exercise identifies assets, trust boundaries, actors, entry points, abuse cases, and likely impact. Developers can then choose controls proportional to risk.

Useful tests include:

  • Unit tests for password, token, and policy behavior.
  • Integration tests for authentication, logout, expiry, CSRF, and ownership rules.
  • Negative tests that verify unauthorized requests are rejected.
  • Fuzz and boundary tests for parsers, uploads, and validation.
  • Dependency and secret scanning in continuous integration.
  • Dynamic testing of deployed APIs.
  • Manual review of high-risk workflows such as account recovery and privilege changes.

A secure status code alone is not enough: a request may return 403 while still leaking sensitive data in the response. Tests should check response body, timing where relevant, side effects, logs, and database changes.

Security has ethical and legal dimensions. Collect the minimum personal data, explain its use, protect it throughout its lifecycle, and respect applicable privacy, breach-notification, accessibility, and records-retention obligations. Authorization policies should avoid unjustified discrimination and should provide accountable processes for exceptional access. Developers must report vulnerabilities responsibly and avoid testing systems without permission.

Chapter Summary

Authentication verifies identity, whereas authorization enforces permitted actions. Passwords should be protected with adaptive password-hashing algorithms such as Argon2id, unique salts, rate limiting, and secure recovery workflows. Server-side sessions and bearer tokens have different operational properties; both require secure transport, expiry, theft mitigation, and revocation planning.

RBAC, permission-based control, and ABAC provide increasingly expressive ways to implement least privilege. Authorization must be enforced on every sensitive backend operation, including object ownership and administrative actions. OAuth 2.0 supports delegated authorization, while OpenID Connect adds identity; authorization-code flow with PKCE, exact redirect handling, state protection, and token validation are central safeguards.

Parameterized queries, context-aware output encoding, schema validation, safe file handling, and controlled error responses reduce injection and data-exposure risk. Secure cookies and CSRF defenses protect browser workflows. SSRF requires URL, DNS, redirect, timeout, and network controls. Secrets management, dependency maintenance, logging, monitoring, threat modeling, and security testing complete the defense-in-depth approach.

Key Terms

Authentication: Verification of a claimed identity.

Authorization: Decision and enforcement concerning permitted actions.

Bearer token: A token that grants access to whoever possesses it.

CSRF: An attack that induces a browser to submit an authenticated request unintentionally.

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

Argon2id: An adaptive password-hashing algorithm designed to resist password cracking.

Hash: A one-way transformation commonly used for integrity or password verification.

Salt: Random non-secret data combined with a password before hashing.

Session fixation: An attack in which an attacker causes a victim to use a known session identifier.

JWT: A signed or encrypted token format carrying claims.

OAuth 2.0: A framework for delegated authorization.

OpenID Connect: An identity layer built on OAuth 2.0.

PKCE: A mechanism that binds an authorization-code exchange to a client-generated verifier.

RBAC: Access control using roles containing permissions.

Least privilege: Granting only the access required for a task.

SSRF: Abuse of a server’s outbound request capability to reach unintended destinations.

Parameterized query: A database query that separates command structure from supplied values.

MFA: Authentication using multiple independent factors.

Secrets manager: A controlled system for storing, accessing, auditing, and rotating secrets.

Review Questions

Short Answer Questions

  1. Distinguish authentication from authorization and give one example of each.
  2. Why is a unique salt used when hashing a password?
  3. State three important security attributes for an authentication cookie.
  4. What problem does PKCE address in an OAuth authorization-code flow?
  5. Why are parameterized queries safer than SQL string concatenation?

Long Answer Questions

  1. Compare server-side sessions and signed access tokens, including revocation, storage, scaling, and major risks.
  2. Explain how RBAC, permission-based access control, and ABAC differ, and describe when each may be appropriate.
  3. Describe a secure password-reset process from request through post-reset session handling.
  4. Explain CSRF and SSRF, comparing their attack mechanisms and defenses.
  5. Develop a defense-in-depth plan for securing a backend API used by browsers and mobile applications.

Analytical / Application Questions

  1. An authenticated learner changes an object identifier in a request and receives another learner’s submission. Identify the vulnerability and propose a database-query and authorization design that prevents it.
  2. A backend preview service accepts arbitrary URLs and follows redirects. Analyze the security risks and specify application and network controls for a safer design.
  3. A team wants to place long-lived JWTs in browser local storage to avoid server-side session state. Evaluate this proposal and recommend a safer architecture, explaining the trade-offs.

Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes authentication from authorization?

A. Authentication verifies identity; authorization determines permitted actions.

B. Authentication encrypts data; authorization compresses data.

C. Authentication assigns database indexes; authorization validates syntax.

D. Authentication prevents all attacks; authorization replaces logging.

Correct Answer: A. Authentication verifies identity; authorization determines permitted actions.

Question 2

What is the primary purpose of a password salt?

A. To make a password reversible by administrators

B. To ensure identical passwords produce different stored hashes

C. To replace the need for an adaptive hashing algorithm

D. To allow passwords to be stored in plaintext safely

Correct Answer: B. To ensure identical passwords produce different stored hashes

Question 3

Which cookie attribute prevents ordinary client-side JavaScript from reading a session cookie?

A. Secure

B. SameSite

C. HttpOnly

D. Path

Correct Answer: C. HttpOnly

Question 4

Why should a session identifier be regenerated after successful login?

A. To increase database storage capacity

B. To prevent session fixation

C. To disable TLS certificate validation

D. To make authorization unnecessary

Correct Answer: B. To prevent session fixation

Question 5

Which approach most directly prevents SQL injection?

A. Concatenating escaped strings manually in every query

B. Using parameterized queries

C. Hiding the database error message only

D. Allowing only administrator users to submit input

Correct Answer: B. Using parameterized queries

Question 6

What does OAuth 2.0 primarily provide?

A. A password-hashing algorithm

B. A delegated authorization framework

C. A database encryption format

D. A replacement for all authorization policies

Correct Answer: B. A delegated authorization framework

Question 7

Which control is most appropriate for reducing CSRF in a cookie-authenticated browser application?

A. Using only GET for state-changing operations

B. Disabling server-side authorization checks

C. Using CSRF tokens together with appropriate cookie policies

D. Placing passwords in URL query parameters

Correct Answer: C. Using CSRF tokens together with appropriate cookie policies

Question 8

Which scenario is an example of SSRF?

A. A user submits a password with insufficient length

B. A server fetches an attacker-selected internal cloud metadata URL

C. A database rejects a duplicate email address

D. A browser blocks a third-party script with CSP

Correct Answer: B. A server fetches an attacker-selected internal cloud metadata URL

Question 9

Which statement about ordinary signed JWTs is correct?

A. Their payload is automatically confidential.

B. Signature verification is unnecessary if the token is well formed.

C. They provide integrity claims but do not automatically provide confidentiality.

D. They cannot expire.

Correct Answer: C. They provide integrity claims but do not automatically provide confidentiality.

Question 10

Which authorization principle grants a subject only the access required for its task?

A. Least privilege

B. Open redirect

C. Implicit trust

D. Shared administration

Correct Answer: A. Least privilege

Backend Development
Chapter 8 of 14