# SAML SSO Single Sign-On Integration

> This document explains how the MaiAgent platform integrates the SAML 2.0 protocol to implement enterprise-grade Single Sign-On (SSO) functionality, ensuring the security and correctness of user authentication.

## 1. What is SAML SSO?

SAML (Security Assertion Markup Language) is an XML-based open standard for exchanging authentication and authorization data between an Identity Provider (IdP) and a Service Provider (SP).

### 1.1 Core Advantages of SAML SSO

| Consideration          | Traditional Multiple Login Approach                                           | SAML SSO Approach                                                                      |
| ---------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| **User Experience**    | Each system requires separate login; passwords are hard to manage             | Single login grants access to multiple systems, improving productivity                 |
| **Security**           | Passwords stored across multiple systems increase leakage risk                | Passwords stored only in the enterprise IdP for centralized and more secure management |
| **Account Management** | Employee departure requires deactivating accounts in each system individually | Deactivating the account in the IdP revokes access to all systems at once              |
| **Compliance**         | Difficult to uniformly audit and manage access records                        | Centralized identity management meets enterprise security compliance requirements      |

### 1.2 Common Use Cases

* **Enterprise Internal System Integration**: Employees log in to MaiAgent using the company's Active Directory or Okta
* **Educational Institutions**: Students and faculty use the school's IdP to access AI learning assistants
* **Multi-tenant SaaS**: Different enterprise customers use their own IdPs to log in to the MaiAgent platform
* **Partner Collaboration**: Allows external partners to access specific resources using their own enterprise accounts

***

## 2. MaiAgent SAML SSO Architecture

{% @mermaid/diagram content="sequenceDiagram
participant User as User
participant Browser as Browser
participant MaiAgent as MaiAgent (SP)
participant IdP as Enterprise IdP

```
User->>Browser: Visit MaiAgent
Browser->>MaiAgent: Request access
MaiAgent->>Browser: Redirect to IdP<br/>(SAML AuthnRequest)
Browser->>IdP: Forward authentication request

IdP->>User: Display login page
User->>IdP: Enter enterprise credentials
IdP->>IdP: Verify user identity

IdP->>Browser: Return SAML Response<br/>(containing user attributes)
Browser->>MaiAgent: POST SAML Response

MaiAgent->>MaiAgent: Verify SAML signature
MaiAgent->>MaiAgent: Parse user attributes<br/>(Email, name, etc.)
MaiAgent->>MaiAgent: Normalize Email<br/>(convert to lowercase)

alt User already exists
    MaiAgent->>MaiAgent: Create login session
else User does not exist
    MaiAgent->>MaiAgent: Automatically create account
end

MaiAgent->>Browser: Redirect to application home
Browser->>User: Display MaiAgent interface" %}
```

### 2.1 Key Component Overview

* **Service Provider (SP)**: The MaiAgent platform acts as the service provider, receiving and verifying SAML responses
* **Identity Provider (IdP)**: The enterprise's authentication system, such as Azure AD, Okta, or Google Workspace
* **SAML Assertion**: An XML document signed by the IdP containing the user's identity and attribute information
* **Metadata Exchange**: SP and IdP exchange configuration information via XML metadata

### 2.2 User Attribute Mapping

MaiAgent extracts the following user attributes from the SAML Assertion:

* **Email (Required)**: Used as the unique user identifier; the system automatically converts it to lowercase for consistency
* **Name**: The user's display name
* **Organization Information**: Department, job title, etc. (depending on IdP configuration)
* **Groups/Roles**: Used for permission management and access control

***

## 3. Email Normalization

### 3.1 Why is Email Normalization Needed?

Email addresses are technically case-insensitive (RFC 5321), but they may appear in different cases across different systems:

* IdP returns: `John.Doe@Company.com`
* User manually enters: `john.doe@company.com`
* API call: `JOHN.DOE@COMPANY.COM`

Without normalization, this could lead to:

* The same user having multiple accounts created
* Incorrect permission checks
* Data inconsistency

### 3.2 MaiAgent's Normalization Strategy

MaiAgent implements the following Email normalization measures in its SAML SSO integration:

The system automatically strips leading and trailing whitespace from Email addresses and converts them to lowercase to ensure consistent account matching.

**Normalization timing**:

1. **When parsing the SAML response**: The user Email is converted to lowercase immediately upon receipt from the IdP
2. **When creating an account**: Email is ensured to be lowercase before creating a new user account
3. **When querying accounts**: Lowercase Email is used when looking up existing users
4. **When storing in the database**: All stored Emails are maintained in lowercase format

### 3.3 Backward Compatibility Handling

For accounts created before the normalization mechanism was implemented, MaiAgent adopts the following strategy:

* **Automatic Migration**: The system automatically converts existing account Emails to lowercase
* **Duplicate Detection**: Checks for duplicate accounts during the conversion process
* **Conflict Resolution**: If conflicts are detected, the earliest created account is retained and data is merged

***

## 4. Automatic Account Creation and Account Conflict Handling

### 4.1 Automatic Account Creation Flow

When a user logs in via SAML SSO for the first time, MaiAgent automatically creates an account:

{% @mermaid/diagram content="flowchart TD
A\["Receive SAML Response"] --> B\["Parse user Email"]
B --> C\["Convert Email to lowercase"]
C --> D{"Does account exist?"}
D -- "Yes" --> E\["Load existing account"]
D -- "No" --> F\["Automatically create new account"]
F --> G\["Set default permissions"]
G --> H\["Create login session"]
E --> H
H --> I\["Redirect to home page"]" %}

**Default settings for automatic creation**:

* **Display Name**: Extracted from the name attribute in the SAML Assertion
* **Default Permissions**: Basic permissions assigned based on organization settings
* **Organization Affiliation**: Determined by Email domain or IdP configuration

### 4.2 Handling Existing Accounts

MaiAgent implements an intelligent account conflict detection and handling mechanism:

* **Email Already Registered**: If a user has previously registered with the same Email (lowercase), they are logged in to the existing account
* **Notification Email**: When an existing account is detected, a notification email is sent to the user
* **Prevent Duplicate Creation**: Database unique constraints ensure the same Email cannot create multiple accounts

### 4.3 Security Considerations

* **Email Verification**: Trusts the Email provided by the IdP since it has already been verified through enterprise identity authentication
* **SAML Signature Verification**: Strictly verifies the digital signature of the SAML Response to prevent forgery
* **Timestamp Validation**: Ensures the SAML Assertion has not expired
* **Replay Attack Protection**: Records used SAML Response IDs to prevent reuse

***

## 5. SAML SSO Configuration Steps

### 5.1 Configuration on the IdP Side

Enterprise IT administrators need to configure the following in the IdP (such as Okta, Azure AD):

1. **Create a new SAML application**
2. **Set MaiAgent's ACS URL** (Assertion Consumer Service URL)
3. **Configure user attribute mappings**, ensuring Email is included
4. **Download the IdP Metadata XML** and provide it to MaiAgent

### 5.2 Configuration on the MaiAgent Side

MaiAgent administrators need to:

1. **Upload the IdP Metadata XML** to the MaiAgent admin panel
2. **Set the Entity ID** to identify this SAML integration
3. **Configure attribute mapping rules** for fields such as Email and name
4. **Enable SAML SSO** and test the login flow

### 5.3 Testing and Verification

After configuration is complete, the following tests are recommended:

* **First Login Test**: Verify that automatic account creation works correctly
* **Repeat Login Test**: Verify that logging in with an existing account works
* **Email Case Test**: Verify that Emails in different cases are correctly recognized
* **Logout Test**: Verify that Single Logout (SLO) functionality works correctly

***

## 6. Technical Advantages of MaiAgent SAML SSO

### 6.1 Security Advantages

* **Enterprise-grade Authentication**: Leverages the enterprise's existing identity management system to ensure consistent authentication standards
* **Passwords Never Pass Through MaiAgent**: User passwords are only verified within the enterprise IdP, reducing leakage risk
* **Centralized Access Control**: IT administrators can manage access permissions for all applications from a single IdP
* **Enforced Multi-factor Authentication**: If the IdP has MFA enabled, users logging in to MaiAgent will also be required to complete MFA

### 6.2 Management Efficiency Advantages

* **Automatic Account Creation**: Reduces the operational burden of manually creating accounts
* **Automatic Account Deactivation**: When an employee leaves and their IdP account is deactivated, MaiAgent access is immediately revoked
* **Attribute Synchronization**: User name, department, and other information changes are automatically synced
* **Audit Records**: All login activities have complete records for security auditing

### 6.3 User Experience Advantages

* **Seamless Login**: If the user is already logged in to the enterprise system, they may not need to enter a password again when accessing MaiAgent
* **Unified Login Interface**: Uses the familiar enterprise login page without requiring additional passwords
* **Mobile Friendly**: Supports SSO experience on mobile devices

***

## 7. Troubleshooting

### 7.1 Common Issues

| Issue                         | Possible Cause                       | Solution                                                                       |
| ----------------------------- | ------------------------------------ | ------------------------------------------------------------------------------ |
| **Unable to Log In**          | SAML signature verification failed   | Verify that the IdP certificate has not expired and the Metadata is up to date |
| **Duplicate Account Created** | Email case inconsistency             | Ensure the system has the Email normalization fix applied                      |
| **Missing Attributes**        | IdP did not send required attributes | Check the IdP's attribute mapping configuration and ensure Email is included   |
| **Timestamp Error**           | Server time out of sync              | Ensure SP and IdP system times are synchronized (NTP recommended)              |

### 7.2 Debugging Tools

* **SAML-tracer**: A browser extension for capturing and analyzing SAML messages
* **MaiAgent Logs**: View detailed SAML processing logs
* **IdP Admin Console**: Check error logs and user attributes on the IdP side

***

## 8. Related Documentation

* [Organization and Member Management](https://docs.maiagent.ai/org/role-permission) - Learn about permission management for SAML users
* [Third-party Login (SSO)](https://docs.maiagent.ai/org/sso) - SSO configuration instructions in the user guide

### Reference Links

* [SAML 2.0 Technical Overview](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html)
* [SAML Security Best Practices](https://www.oasis-open.org/committees/download.php/56776/sstc-saml-sec-consider-2.0-os.pdf)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.maiagent.ai/tech/maiagent-tech-en/advanced-genai-tech/saml-sso.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
