Authentication and Authorization

Authentication and authorization form the backbone of security in distributed systems. Authentication verifies who a user is, while authorization determines what they’re allowed to do. These complementary processes ensure that only legitimate users can access appropriate resources within a system.

OAuth (Open Authorization)

OAuth is an open standard authorization framework that enables third-party applications to access user data without requiring users to share their passwords. This delegation-based approach has become the foundation for secure data sharing across modern web applications.

OAuth Architecture and Roles

OAuth operates through four distinct roles that work together to facilitate secure authorization:

┌─────────────────┐    ┌─────────────────┐
│  Resource Owner │    │     Client      │
│   (End User)    │    │ (Third-party    │
│                 │    │  Application)   │
└─────────────────┘    └─────────────────┘
         │                       │
         │                       │
         ▼                       ▼
┌─────────────────┐    ┌─────────────────┐
│ Authorization   │    │  Resource       │
│    Server       │    │   Server        │
│ (Issues tokens) │    │ (Hosts data)    │
└─────────────────┘    └─────────────────┘

Resource Owner: The end user who owns the data and has the authority to grant access to it.

Client: The third-party application that wants to access the user’s data on their behalf.

Authorization Server: The service responsible for authenticating the user and issuing access tokens after proper authorization.

Resource Server: The server that hosts the protected resources and validates access tokens before serving data.

OAuth Authorization Flow

The OAuth process follows a structured sequence that ensures security while maintaining user control:

  1. Authorization Request: The client redirects the user to the authorization server with specific parameters including client ID, requested scope, and redirect URI.
  2. User Authentication: The authorization server authenticates the user and presents them with a consent screen showing what permissions the client is requesting.
  3. Authorization Grant: If the user approves, the authorization server provides an authorization code to the client via the redirect URI.
  4. Token Exchange: The client exchanges the authorization code for an access token by making a secure request to the authorization server’s token endpoint.
  5. Resource Access: The client uses the access token to make authenticated requests to the resource server.

OAuth Token Types

OAuth utilizes different types of tokens for various purposes:

Access Tokens: Short-lived tokens that grant access to specific resources. These are presented to resource servers to authenticate API requests.

Refresh Tokens: Long-lived tokens used to obtain new access tokens when the current ones expire, eliminating the need for repeated user authentication.

Authorization Codes: Temporary codes exchanged for access tokens, providing an additional security layer in the authorization flow.

OAuth Advantages and Considerations

OAuth provides significant security benefits by eliminating password sharing between applications. Users maintain control over their data through granular permission systems, and applications can access only the specific resources they need. The framework supports token expiration and revocation, enabling fine-grained access control.

However, OAuth’s multi-step flow and multiple components can introduce complexity. Proper implementation requires careful attention to security details, including secure token storage, proper scope validation, and protection against common vulnerabilities like CSRF attacks.

JSON Web Tokens (JWT)

JSON Web Tokens represent a compact, self-contained method for securely transmitting information between parties. JWTs have become particularly popular for stateless authentication in distributed systems due to their portability and ease of verification.

JWT Structure

A JWT consists of three Base64-encoded sections separated by dots:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
└─────────── Header ────────────┘    └─────────── Payload ────────────┘                                         └─────── Signature ──────┘

Header: Contains metadata about the token, including the signing algorithm (e.g., HMAC SHA256, RSA) and token type. This information helps the verifying party understand how to process the token.

Payload: Contains the claims - statements about the user and additional metadata. Claims can be registered (standardized), public (defined by the application), or private (custom claims for specific use cases).

Signature: Created by combining the encoded header and payload with a secret key using the specified algorithm. This ensures the token hasn’t been tampered with and verifies its authenticity.

JWT Claims

JWTs support various types of claims that provide information about the user and token:

Standard Claims: Include issuer (iss), subject (sub), audience (aud), expiration time (exp), and issued at (iat). These provide essential metadata for token validation.

Custom Claims: Application-specific information such as user roles, permissions, or other business logic data needed for authorization decisions.

JWT Workflow

The JWT authentication process follows these steps:

  1. Token Generation: After successful user authentication, the server creates a JWT containing relevant user information and signs it with a secret key.
  2. Token Storage: The client receives the JWT and stores it securely, typically in memory, secure cookies, or local storage with appropriate security measures.
  3. Token Transmission: For subsequent requests, the client includes the JWT in the Authorization header using the Bearer schema.
  4. Token Verification: The server validates the JWT signature, checks expiration, and extracts claims to make authorization decisions.

JWT Benefits and Trade-offs

JWTs offer stateless authentication, eliminating the need for server-side session storage. This characteristic makes them ideal for distributed systems where multiple services need to verify user identity without shared session state. The self-contained nature of JWTs enables horizontal scaling and reduces database lookups for user information.

However, JWTs can become large when they contain extensive claims, potentially impacting network performance. Token revocation presents challenges since JWTs are stateless - implementing token blacklists or short expiration times becomes necessary for security. Additionally, sensitive information should never be stored in JWT payloads since they can be decoded without the signing key.

Single Sign-On (SSO)

Single Sign-On enables users to authenticate once and access multiple applications without repeated login prompts. This approach significantly improves user experience while providing centralized identity management for organizations.

SSO Architecture

                    ┌─────────────────┐
                    │   Identity      │
                    │   Provider      │
                    │    (IdP)        │
                    └─────────────────┘
                             │
                    ┌────────┼────────┐
                    │        │        │
                    ▼        ▼        ▼
            ┌──────────┐ ┌──────────┐ ┌──────────┐
            │   App A  │ │   App B  │ │   App C  │
            │ (Email)  │ │   (HR)   │ │ (Finance)│
            └──────────┘ └──────────┘ └──────────┘

SSO Process Flow

  1. Initial Authentication: The user attempts to access an application that requires authentication.
  2. Redirect to Identity Provider: The application redirects the user to the configured identity provider for authentication.
  3. User Authentication: The identity provider authenticates the user using credentials, multi-factor authentication, or other methods.
  4. Token/Assertion Generation: Upon successful authentication, the identity provider generates a security token or assertion containing user identity information.
  5. Application Access: The user is redirected back to the original application with the authentication token, granting access.
  6. Subsequent Access: When accessing other SSO-enabled applications, the existing authentication session allows immediate access without re-authentication.

SSO Protocols

  • SAML (Security Assertion Markup Language): An XML-based standard for exchanging authentication and authorization data between identity providers and service providers. SAML is widely used in enterprise environments.
  • OAuth/OpenID Connect: Modern protocols are often used for SSO implementation, particularly in web and mobile applications.
  • Kerberos: A network authentication protocol commonly used in Windows Active Directory environments for SSO within corporate networks.

SSO Advantages and Considerations

SSO dramatically improves user experience by reducing password fatigue and login friction. Organizations benefit from centralized user management, simplified access control, and reduced help desk tickets related to password issues. Security can be enhanced through centralized authentication policies and stronger authentication methods.

However, SSO creates a single point of failure - if the identity provider becomes unavailable, users cannot access any connected applications. This risk necessitates robust infrastructure design and backup authentication methods. Organizations must also carefully manage session timeouts and implement proper logout procedures to prevent unauthorized access.

OpenID Connect (OIDC)

OpenID Connect builds upon OAuth 2.0 to provide a standardized authentication layer. While OAuth handles authorization, OIDC adds identity verification capabilities, making it suitable for authentication scenarios.

OIDC Components

OIDC extends OAuth 2.0 with additional elements:

  • ID Token: A JWT that contains identity information about the authenticated user, including claims like user ID, email, and profile information.
  • UserInfo Endpoint: An API endpoint that provides additional user profile information when accessed with a valid access token.
  • Discovery Document: A well-known endpoint that provides metadata about the OIDC provider’s configuration and capabilities.

OIDC Flow

┌─────────┐    ┌─────────────┐    ┌─────────────┐
│  User   │    │ Application │    │    OIDC     │
│         │    │  (Client)   │    │  Provider   │
└─────────┘    └─────────────┘    └─────────────┘
     │                │                    │
     │  Access App    │                    │
     │──────────────▶ │                    │
     │                │                    │
     │                │  Auth Request      │
     │                │──────────────────▶ │
     │                │                    │
     │  Login Page    │                    │
     │◀────────────────────────────────────│
     │                │                    │
     │  Credentials   │                    │
     │───────────────────────────────────▶ │
     │                │                    │
     │                │  Auth Code         │
     │                │◀───────────────────│
     │                │                    │
     │                │  Token Request     │
     │                │──────────────────▶ │
     │                │                    │
     │                │  ID Token +        │
     │                │  Access Token      │
     │                │◀───────────────────│
     │                │                    │
     │  Authenticated │                    │
     │◀───────────────│                    │

OIDC vs OAuth Distinction

While OAuth 2.0 focuses on authorization (“what can this application do?”), OIDC addresses authentication (“Who is this user?”). OAuth provides access tokens for API access, while OIDC adds ID tokens that contain user identity information. This distinction makes OIDC suitable for login scenarios where applications need to know user identity, not just access permissions.

OIDC Advantages

OIDC provides standardized authentication across different platforms and providers. The protocol supports social login scenarios where users can authenticate using existing accounts from Google, Facebook, Microsoft, or other providers. ID tokens provide structured user information in a standardized format, simplifying integration for applications.

The protocol also supports various authentication flows optimized for different application types, from web applications to mobile apps and single-page applications. Built-in security features include token validation, audience verification, and replay attack protection.

Role-Based Access Control (RBAC)

Role-Based Access Control simplifies permission management by organizing access rights around roles rather than individual users. This approach scales well in organizations with defined job functions and hierarchical structures.

RBAC Model

┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│    Users    │    │    Roles    │    │ Permissions │
│             │    │             │    │             │
│  • Alice    │    │  • Admin    │    │  • Read     │
│  • Bob      │    │  • Manager  │    │  • Write    │
│  • Carol    │    │  • Viewer   │    │  • Delete   │
│  • David    │    │  • Editor   │    │  • Execute  │
└─────────────┘    └─────────────┘    └─────────────┘
       │                   │                   │
       └─────────────┐     │     ┌─────────────┘
                     ▼     ▼     ▼
               ┌─────────────────────┐
               │  Role Assignments   │
               │                     │
               │  Alice → Admin      │
               │  Bob → Manager      │
               │  Carol → Viewer     │
               │  David → Editor     │
               └─────────────────────┘

RBAC Components

  • Users: Individual entities that need access to system resources.
  • Roles: Collections of permissions that correspond to job functions or responsibilities within an organization.
  • Permissions: Specific actions that can be performed on resources (read, write, delete, execute).
  • Role Assignments: The mapping between users and their assigned roles.

RBAC Implementation

RBAC systems typically implement hierarchical role structures where higher-level roles inherit permissions from lower-level roles. For example, a Manager role might inherit all Viewer permissions while adding additional management capabilities.

Permission inheritance can be implemented through:

  • Role Hierarchies: Structured relationships between roles
  • Permission Inheritance: Automatic permission propagation through role levels
  • Constraint Enforcement: Rules that prevent conflicting role assignments

RBAC Benefits

RBAC provides administrative simplicity by grouping permissions into meaningful roles. This approach reduces the complexity of permission management and makes it easier to understand who has access to what resources. Role-based systems also support regulatory compliance by providing clear audit trails and access control documentation.

The model scales well for large organizations where hundreds or thousands of users can be managed through a relatively small number of roles. Changes to job functions can be handled by modifying role definitions rather than individual user permissions.

Attribute-Based Access Control (ABAC)

Attribute-Based Access Control represents a more sophisticated approach to access control, making decisions based on multiple attributes associated with users, resources, and environmental conditions.

ABAC Model

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ User Attributes │    │ Resource        │    │ Environmental   │
│                 │    │ Attributes      │    │ Attributes      │
│ • Role          │    │                 │    │                 │
│ • Department    │    │ • Classification│    │ • Time          │
│ • Clearance     │    │ • Owner         │    │ • Location      │
│ • Project       │    │ • Sensitivity   │    │ • Network       │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 ▼
                    ┌─────────────────────┐
                    │   Policy Engine     │
                    │                     │
                    │  IF user.role =     │
                    │     "Doctor" AND    │
                    │  resource.type =    │
                    │     "PatientRecord" │
                    │  AND time.hour      │
                    │     BETWEEN 8-18    │
                    │  THEN PERMIT        │
                    └─────────────────────┘

ABAC Attributes

  • Subject Attributes: Characteristics of the user requesting access, such as role, department, security clearance, or project membership.
  • Resource Attributes: Properties of the resource being accessed, including classification level, owner, data type, or sensitivity rating.
  • Environmental Attributes: Contextual information about the access request, such as time of day, location, network security level, or device type.
  • Action Attributes: Details about the requested operation, such as read, write, delete, or execute.

ABAC Policy Structure

ABAC policies are typically expressed as rules that evaluate multiple attributes:

Policy: Medical Records Access
Rule: PERMIT
Condition: 
  subject.role = "Doctor" AND
  subject.department = resource.department AND
  resource.type = "PatientRecord" AND
  environment.time BETWEEN 08:00-18:00 AND
  environment.location = "Hospital"

ABAC Advantages and Complexity

ABAC provides unprecedented flexibility in access control, supporting complex scenarios that RBAC cannot handle effectively. The model can adapt to dynamic environments where access requirements change based on context, time, or other factors.

For example, a healthcare system might allow doctors to access patient records only during working hours, from hospital locations, and only for patients in their department. This level of granular control is difficult to achieve with traditional RBAC systems.

However, ABAC complexity can be significant. Policy management becomes more challenging as the number of attributes and rules increases. Organizations must invest in proper tooling for policy creation, testing, and maintenance. The attribute management infrastructure must be robust and performant to handle real-time access decisions.

ABAC vs RBAC Comparison

┌─────────────────┬─────────────────┬─────────────────┐
│   Aspect        │      RBAC       │      ABAC       │
├─────────────────┼─────────────────┼─────────────────┤
│ Complexity      │     Simple      │    Complex      │
│ Flexibility     │    Limited      │     High        │
│ Scalability     │     Good        │   Excellent     │
│ Policy Mgmt     │     Easy        │   Challenging   │
│ Implementation  │  Straightforward│   Sophisticated │
│ Use Cases       │  Stable Orgs    │ Dynamic Envs    │
└─────────────────┴─────────────────┴─────────────────┘

The choice between RBAC and ABAC depends on organizational needs, security requirements, and the complexity of access control scenarios. Many modern systems implement hybrid approaches, using RBAC for basic access control and ABAC for more sophisticated scenarios requiring contextual decision-making.

Track your progress

Mark this subtopic as completed when you finish reading.