Web Programming
Lecture 12

User authentication and authorization

Josue Obregon

Seoul National University of Science and Technology
Information Technology Management
Lecture slides index

May 27, 2025

Agenda

  • Authentication and authorization
  • OAuth
  • JWT

Course structure

Roadmaps: Frontend, backend and fullstack

The importance of security

  • Security was once an afterthought—but not anymore. Apps today are:
    • Exposed 24/7 to the internet
    • Handling sensitive business and user data
    • Built on complex layers and third-party dependencies
  • Developers are the first line of defense, even in teams with dedicated security staff.
  • Social engineering is now the most common attack vector, it’s easier to trick humans than hack code.
  • Real business impact: Data breaches cause reputation loss, legal risk, and customer harm.
    • You can check whether your email address has been compromised in a data breach in this site

Security in web applications and APIs

  • APIs often handle sensitive data and business logic.
    • Exposing user info, booking details, payment history.
  • Attackers target APIs due to weak endpoints or missing checks.
  • Common vulnerabilities presented by the Open Web Application Security Project (OWASP) WebApps Top 10 and API Top 10:

OWASP top 3 vulnerabilities

  • Broken Access Control: Occurs when users can act outside their authorized roles, accessing or modifying data/functions.
    • Examples: URL tampering, privilege escalation, insecure object references, or broken JWT validation.
    • How to prevent: Enforce access checks server-side; deny access by default except for public resources.
  • Criptographic Failures: Happens when sensitive data (e.g., passwords, credit card information) is exposed due to missing or weak encryption.
    • Risks include using outdated algorithms, transmitting data in clear text, or improper key handling.
    • How to prevent: Encrypt all sensitive data in transit (TLS) and at rest using strong, modern standards.Avoid weak/deprecated crypto (e.g., MD5), use secure password hashing (bcrypt, Argon2), and enforce key management best practices.
  • Injection: Injection flaws happen when untrusted input is sent to an interpreter (e.g., SQL) as part of a command or query. If inputs aren’t properly validated or parameterized, attackers can manipulate queries and access or modify data.
    • Use safe APIs or ORMs that support parameterized queries.
    • Validate inputs, avoid dynamic query building, and use query controls like LIMIT to restrict data exposure.

Authentication and Authorization

  • Authentication confirms the identity of a user, typically through login credentials like username and password.
    • It might includes Multi-Factor Authentication (MFA) for added assurance.
  • Authorization determines what actions or resources a user is allowed to access after they are authenticated.
    • Based on permissions, roles, or scopes.
  • These two concepts are often confused but serve distinct purposes in securing web applications.
    • Key Difference: Authentication = “You are user12345.” Authorization = “user12345 can view flights but cannot add new flights.””
  • Implementing both correctly ensures that only verified users can access permitted parts of the application.

Types of authentication

  • Authentication is typically performed by having a user present a user identifier along with a credential, such as a password, a one-time SMS code, or an assertion signed with a private key.
    • The system then checks the binding between the user identifier and the credential, so it can decide whether or not to authenticate the user.
  • Types of authentication information, also called authentication factors, are commonly presented in three categories:
    • Something the user knows, such as a password.
    • Something the user has, such as a phone.
    • Something the user is, such as a thumbprint (biometric identifier).
  • Multi-factor authentication (MFA) systems require the user to provide more than one factor: for example, a password combined with a one-time code sent to the user’s phone.
  • The most common ways for web authentication are:
    • Username and password.
    • Token-based authentication, such as using JSON Web Tokens (JWT), common in RESTful APIs.
    • Session-based authentication.

Authorization

  • Authorization determines what actions a user is allowed to perform after authentication.
  • Common examples:
    • Can the user access a specific page?
    • Can the user create, edit, or delete a post?
  • In modern web systems, users often have roles (e.g., admin, editor, viewer).
  • Role-Based Access Control (RBAC) is the most common authorization type:
    • Permissions are grouped by roles.
    • Users are assigned one or more roles.
    • Actions are allowed/denied based on role permissions.
  • Skipping authorization checks can expose pages or actions to all users.
  • Always verify access rights for each route and action on both front-end and back-end.

OAuth 2.0: Delegated Authorization

  • OAuth 2.0 is a token-based authorization framework.
  • It allows users to grant third-party apps access to their data without sharing credentials.
  • Used by major providers like Google, Meta, GitHub.
  • Ideal for secure delegation: “App A can access my calendar, but not my contacts.”
  • Roles in Oauth 2.0:
    • Resource Owner: The user who owns the data (e.g., you).
    • Client: The application requesting access on the user’s behalf (e.g., a calendar app).
    • Authorization Server: Authenticates the user and issues access tokens (e.g., Google OAuth server).
    • Resource Server: Hosts the protected data and validates access tokens (e.g., Google Calendar API).

OAuth 2.0 abstract protocol flow

  1. The client requests authorization from the resource owner.
  2. The resource owner will grant or deny the client access to their resources.
  3. The client will ask for an access token from the authorization server for the authorization it has been granted.
  4. The authorization server will issue an access token if the client has been authorized by the resource owner.
  5. The client makes a request for the resource to the resource server, which in our case is the API. The request will send the access token as part of the request.
  6. The resource server will return the resource if the access token is valid.

JSON Web Token (JWT)

  • One of the most popular ways to implement authentication and authorization in a web application is to use JWT.
  • JSON Web Token is a proposed internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. - The tokens are signed either using a private secret or a public/private key.
  • Basically, a JWT is a string (JSON) that contains information (claims) and is signed using a secret key.
  • JWTs allow stateless authentication, meaning the server doesn’t need to store session data — this makes scaling across multiple servers much easier.
  • Each request must be considered untrusted by default, so JWTs include a signed payload that lets the server verify the token’s integrity without storing user state.
  • JWT signatures protect against unauthorized alterations, ensuring that any changes to the token can be detected, providing both authenticity and security in every request.

JWT process

  • In plain terms, the user will authenticate using a username and password, and then the server will return a JWT.
  • The user will send the JWT in every request and the server will verify the JWT to authenticate the user
  • The JWT is a string with information about the user (such as their name, role, etc.) and is signed using a secret key.
  • The server can verify the JWT using the secret key and can then extract the information about the user.
  • Any attempt to modify the JWT will invalidate the signature, so the server will reject the request.

sequenceDiagram
    participant Client
    participant Server

    Client->>Server: Send login credentials
    Server->>Server: Create JWT
    Server-->>Client: Return JWT
    Client->>Server: Send request with JWT
    Server->>Server: Verify JWT
    Server-->>Client: Respond with protected resource

Hashing

  • Hashing transforms any input into a fixed-length string using a one-way algorithm.
    • MD5 (broken), SHA1 (weak), SHA256 (standard), bcrypt (adaptive).
  • It’s not reversible: you can’t get the original input back from the hash.
  • Hashes are used to verify data integrity, especially for sensitive info like passwords.
const bcrypt  = require('bcrypt');
const hash = await bcrypt.hash('Hello World', 10);
console.log(hash);
// Output:  $2b$10$9Nub0LuSmYa5vOPo.h.9DOh09Cnor/nXSPpakMK2N6D/ZKZdAW1yq
  • We’ll use hashing to store passwords securely during user authentication.
  • Why store hashes of passwords instead of the actual passwords?

Signing

  • Signing takes content + a secret (or private key) to produce a signature.
  • Unlike hashing, signatures can be verified using the original secret or a public key.
  • This proves both authenticity (who signed it) and integrity (it wasn’t altered).
  • For example, Node.js releases include a signed hash file (e.g., SHASUMS256.txt)
  • Verifying both the hash and signature ensures the file is authentic and untampered.
  • In JWTs, we use a similar pattern: the payload is hashed and signed (e.g., with HMAC or RSA) instead of using PGP.

sequenceDiagram
    participant Sender
    participant Receiver

    Sender->>Sender: Create message
    Sender->>Sender: Sign message with PRIVATE key
    Sender-->>Receiver: Send message + signature
    Receiver->>Receiver: Verify signature using PUBLIC key
    Receiver->>Receiver: Confirm authenticity and integrity

JWT structure

  • JWT is a string that is composed of three parts separated by a dot. Each part is encoded in base64.
    • Header: Contains information about the type of token and the algorithm used to sign the token
    • Payload: Contains the claims (information) that we want to store in the token. Example claims: iss(issuer, like Google or Auth0), sub (subject), exp(expiration time), nbf (not before), iat(issued at) and jti (JWT identifier)
    • Signature: Contains the signature of the token that is used to verify the token
      • The signature is the result of signing the header and the payload using the secret key.
  • We can verify the signature using the secret key, so we can verify the token without needing to store any information on the server.

Header

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": "true",
  "iat": 1516239022
}

JWT token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30

Next week

  • CI and CD in web applications

Acknowledgements


Back to title slide Back to lecture slides index