> For the complete documentation index, see [llms.txt](https://oten.gitbook.io/identity-support/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://oten.gitbook.io/identity-support/integration/understand-sso-flow/overview.md).

# Overview

This section explains how Single Sign-On works behind the scenes. Understanding this flow helps both developers implement SSO correctly and end users understand what's happening during login.

## 🎯 Learning Objectives

After reading this section, you'll understand:

* The complete SSO authentication flow
* What happens at each step
* The role of different components
* How tokens work in SSO
* Security considerations

## 🏗️ SSO Architecture Overview

### Key Components

#### 1. User's Browser

* Where the user interacts with applications
* Handles redirects between application and IDP
* Stores session cookies (temporarily)

#### 2. Your Application

* **Frontend**: User interface, login buttons
* **Backend**: Handles OAuth flow, stores tokens securely

#### 3. Oten IDP

* **Identity Provider**: Authenticates users
* **Token Service**: Issues and validates tokens
* **User Store**: Manages user accounts and profiles

### Detailed Step-by-Step Process

#### Step 1: User Initiates Login

```
User Action: Clicks "Login" button
Application: Checks if user is authenticated
Result: User needs to authenticate
```

#### Step 2: Generate PKCE Parameters

```
Application: Generates code_verifier (random string)
Application: Creates code_challenge from code_verifier using SHA256
Application: Stores code_verifier for later use
Security: PKCE prevents authorization code interception
```

#### Step 3: Create JAR (JWT-Secured Authorization Request)

```
Application: Creates authorization parameters:
  - response_type: "code"
  - client_id: "your_client_id"
  - redirect_uri: "https://yourapp.com/callback"
  - scope: "openid profile email"
  - state: "random_state_string" (CSRF protection)
  - nonce: "random_nonce_string"
  - code_challenge: generated from step 2
  - code_challenge_method: "S256"

Application: Signs parameters as JWT using client_secret (HS256)
Security: JAR ensures request integrity and authenticity
```

#### Step 4: Redirect to Authorization Endpoint

```
Application: Creates authorization URL with JAR:
URL: https://account.oten.com/v1/oauth/authorize?client_id=your_client_id&request=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Browser: Redirects user to Oten IDP
Note: Traditional OAuth query parameters are NOT supported
```

#### Step 5: User Authenticates at IDP

```
IDP: Validates JAR signature and parameters
IDP: Shows login form
User: Enters username/password
IDP: Validates credentials
Optional: Two-factor authentication
IDP: User grants consent for requested scopes
```

#### Step 6: IDP Issues Authorization Code

```
IDP: Creates temporary authorization code (10-minute expiry)
IDP: Validates redirect_uri matches registered URI
Browser: Redirects back to application with code and state
URL: https://yourapp.com/callback?code=abc123&state=xyz789
```

#### Step 7: Handle Callback and Validate

```
Application: Parses callback parameters (code, state, error)
Application: Validates state parameter matches stored value
Application: Checks for authorization errors
Security: State validation prevents CSRF attacks
```

#### Step 8: Exchange Code for Tokens

```
Application: Sends POST request to token endpoint:
  - grant_type: "authorization_code"
  - code: received authorization code
  - redirect_uri: must match authorization request
  - client_id: application identifier
  - code_verifier: PKCE verifier from step 2
  - client_secret: for confidential clients

IDP: Validates code, client credentials, and PKCE verifier
IDP: Returns token response:
  - access_token: for API calls (1 hour expiry)
  - refresh_token: for token renewal (long-lived)
  - id_token: user information (JWT format)
  - expires_in: token lifetime in seconds
```

#### Step 9: Store and Use Tokens

```
Application: Stores tokens securely (sessionStorage for web apps)
Application: Extracts user info from ID token
Application: Uses access token for protected API calls
User: Successfully logged in and can access application
```

#### Step 10: Token Management

```
Application: Monitors token expiration
Application: Automatically refreshes tokens using refresh_token
Application: Handles token refresh failures (redirect to login)
Application: Provides logout functionality (clears stored tokens)
```

## 🎫 Understanding Tokens

### Authorization Code

* **Purpose**: Temporary code to exchange for tokens
* **Lifetime**: Very short (usually 10 minutes)
* **Security**: Single-use only
* **Example**: `abc123def456ghi789`

### Access Token

* **Purpose**: Grants access to protected resources
* **Lifetime**: Short (15-60 minutes)
* **Format**: Usually JWT (JSON Web Token)
* **Usage**: Sent with API requests

### Refresh Token

* **Purpose**: Obtains new access tokens
* **Lifetime**: Long (days to months)
* **Security**: Stored securely, can be revoked
* **Usage**: Automatic token renewal

### ID Token

* **Purpose**: Contains user identity information
* **Format**: JWT with user claims
* **Contents**: User ID, email, name, etc.
* **Usage**: Application knows who the user is

## 🔐 Security Mechanisms

### State Parameter

* **Purpose**: Prevents CSRF attacks
* **How it works**: Random value sent and verified
* **Implementation**: Generated by app, validated on return

### PKCE (Proof Key for Code Exchange)

* **Purpose**: Secures public clients (SPAs, mobile)
* **How it works**: Code challenge/verifier pair
* **Required for**: Applications that can't store secrets

### Nonce

* **Purpose**: Prevents replay attacks
* **How it works**: Random value in ID token
* **Usage**: OpenID Connect flows

## ⏱️ Session Management

### Session Lifecycle

1. **Login**: User authenticates, session created
2. **Active**: User accesses applications
3. **Refresh**: Tokens renewed automatically
4. **Timeout**: Session expires due to inactivity
5. **Logout**: User explicitly logs out

### Session Duration

* **Access tokens**: 15-60 minutes
* **Refresh tokens**: 7-30 days
* **ID tokens**: Same as access tokens
* **SSO session**: 8-24 hours (configurable)

### Cross-Application Sessions

* **Single logout**: Logging out of one app logs out of all
* **Session sharing**: Login to one app grants access to others
* **Centralized control**: IT can revoke access globally

## 🔍 Monitoring and Observability

### What to Monitor

* **Login success/failure rates**
* **Token refresh patterns**
* **Session duration statistics**
* **Error rates by type**
* **Performance metrics**

### Logging Best Practices

* **Log authentication events**
* **Don't log sensitive data** (passwords, tokens)
* **Include correlation IDs**
* **Monitor for suspicious patterns**

## 🚨 Error Scenarios

### Common Error Flows

1. **Invalid credentials**: User enters wrong password
2. **Expired code**: Authorization code takes too long to exchange
3. **Invalid client**: Application not properly registered
4. **Access denied**: User cancels authentication
5. **Server errors**: IDP temporarily unavailable

### Error Handling Strategy

* **User-friendly messages**: Don't expose technical details
* **Retry mechanisms**: Handle temporary failures gracefully
* **Fallback options**: Provide alternative authentication methods
* **Monitoring**: Alert on error rate spikes

***

**Next**: Dive deeper into the [Flow Diagram](broken://pages/7g0Zu0FHduTvKHgpoGNv) to see the technical details
