> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/en/identity-and-access/sso-overview/saml-sso.md).

# SAML SSO Integration

SAML SSO integration: IdP and SP architecture, email normalization, automatic account creation and conflict handling, configuration steps, limitations, and troubleshooting.

> This document describes the technical specifications of the MaiAgent platform as a SAML 2.0 Service Provider (SP): the login flow, user attributes it reads, account creation and matching rules, and information needed for configuration. For administration screens and step-by-step Microsoft Entra ID configuration, see “[SAML Integration](https://docs.maiagent.ai/org/sso/sso-saml)” in the user manual.

## 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).

{% hint style="info" %}
For the benefits and use cases of SAML SSO, see “[Third-Party Login (SSO)](https://docs.maiagent.ai/org/sso)” in the user manual.
{% endhint %}

***

## 2. MaiAgent SAML SSO Architecture

```mermaid
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: Authenticate user

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

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

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

    MaiAgent->>Browser: Redirect to application home page
    Browser->>User: Display MaiAgent interface
```

### 2.1 Key Components

* **Service Provider (SP)**: The MaiAgent platform acts as the service provider, receiving and validating SAML responses
* **Identity Provider (IdP)**: The enterprise authentication system, such as Azure AD, Okta, or Google Workspace
* **SAML Assertion**: An XML document signed by the IdP that contains the user's identity and attributes
* **IdP Configuration Source**: MaiAgent can automatically read IdP settings from an IdP Metadata URL, or an administrator can manually enter the Entity ID, SSO URL, and X.509 certificate (see Section 5.2)

### 2.2 User Attribute Mapping

MaiAgent reads only **email** and **display name**. The mapping rules are fixed and **cannot be customized in the administration interface**; other attributes such as department, job title, groups, and roles are not read.

| Purpose          | Attributes MaiAgent Reads (in Order)                                                                                                                                                                                                                                                                                                                                         | Description                                                                                                                                           |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Email (required) | <p>1. <code><http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name></code> (default output from Microsoft Entra ID and ADFS)<br>2. <code>urn:oid:0.9.2342.19200300.100.1.3</code> or <code><http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress></code><br>3. NameID with format <code>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</code></p> | Converted to lowercase and used as the account identifier. Login fails if none of these three is present                                              |
| Display Name     | `http://schemas.microsoft.com/identity/claims/displayname`                                                                                                                                                                                                                                                                                                                   | Written only when creating the account at first login. If absent, the text before the email's @ or the name attribute sent by the IdP is used instead |

Ensure the IdP sends at least one of the email attributes listed above.

***

## 3. Email Normalization

### 3.1 Why Is Email Normalization Needed?

Email addresses are technically case-insensitive (RFC 5321), but may appear with different capitalization across systems:

* Returned by the IdP: `John.Doe@Company.com`
* Entered manually by the user: `john.doe@company.com`
* Used in an API call: `JOHN.DOE@COMPANY.COM`

Without normalization, this may lead to:

* Multiple accounts created for the same user
* Incorrect permission decisions
* Inconsistent data

### 3.2 MaiAgent's Normalization Strategy

The system converts all email addresses to lowercase to ensure consistent account matching.

**When Normalization Occurs**:

1. **When Parsing SAML Responses**: Converts the user's email to lowercase immediately after receiving it from the IdP
2. **When Looking Up Accounts**: Uses the lowercase email to find existing users
3. **When Storing in the Database**: Always stores emails in lowercase when saving user accounts

***

## 4. Automatic Account Creation and Account Conflict Handling

### 4.1 Automatic Account Creation Flow

MaiAgent automatically creates an account when a user first logs in through SAML SSO:

```mermaid
flowchart TD
    A["Receive SAML Response"] --> B["Parse user email"]
    B --> C["Convert email to lowercase"]
    C --> D{"Does the account exist?"}
    D -- "Yes" --> E["Load existing account"]
    D -- "No" --> F["Automatically create new account"]
    F --> H["Create login session"]
    E --> H
    H --> I["Redirect to home page"]
```

**Settings Applied During Automatic Creation**:

* **Display Name**: Obtained according to the rules in Section 2.2
* **Login Source**: Set to this SAML authentication source
* **Organization Membership**: If this authentication source has a default organization, the account automatically joins it as a member
* **Role**: SAML does not transmit or synchronize roles; the organization administrator assigns member roles in the MaiAgent administration interface

### 4.2 Handling Existing Accounts

* **Email Already Registered**: If the user previously registered with the same email (in lowercase), they log directly into the existing account; its login source changes to this SAML authentication source, and it joins this source's default organization
* **No Notification Email**: Existing accounts are linked directly without sending a notification email to the user
* **Preventing Duplicate Creation**: A database Unique Constraint ensures that multiple accounts cannot be created for the same email

### 4.3 Security Considerations

* **Email Verification**: Trusts the email provided by the IdP, as it has already passed enterprise authentication
* **SAML Signature Validation**: Strictly validates the digital signature of the SAML Response to prevent forgery
* **Timestamp Checks**: Ensures the SAML Assertion has not expired
* **Initiate Login from MaiAgent**: Start SSO login from the MaiAgent login page. Login initiated directly from the IdP portal (IdP-initiated) may not complete; contact your MaiAgent representative if you need this capability

***

## 5. SAML SSO Configuration Steps

### 5.1 Configure the IdP

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

1. **Create a New SAML Application**
2. **Enter MaiAgent's SP Information**:

   * Entity ID (Audience URI): `{MaiAgent 後端網址}/accounts/saml/{認證來源名稱}/metadata/`
   * ACS URL (Reply URL): `{MaiAgent 後端網址}/accounts/saml/{認證來源名稱}/acs/`

   After saving the SAML settings in MaiAgent, both URLs appear in the “Service Provider Information” section of the settings page and can be copied directly.

   These values serve different purposes: **Entity ID** identifies MaiAgent as an SP, allowing the IdP to determine the Assertion's intended recipient (Audience). **ACS URL** (Assertion Consumer Service) is the MaiAgent endpoint to which the IdP sends the signed SAML Response via a browser POST after the user successfully logs in at the IdP. MaiAgent validates the signature, reads the email attribute, and completes login at this endpoint. The IdP sends responses only to the preregistered ACS URL, so it must exactly match the value shown in MaiAgent, including the trailing `/`. If it is incorrect, the IdP rejects the request or MaiAgent does not receive the response. This differs from MaiAgent's login entry point (`/auth/saml/{認證來源名稱}/login/`, the URL users are redirected to when they click “SSO Login”).
3. **Ensure an Email Attribute Is Sent**: Send any email attribute listed in Section 2.2; also send `displayname` to display the user's name
4. **Obtain IdP Settings**: The IdP Metadata URL, or the IdP Entity ID, SSO URL, and X.509 certificate

### 5.2 Configure MaiAgent

In organization settings, the MaiAgent administrator selects <mark style="color:blue;">SAML</mark> under <mark style="color:blue;">Third-Party Login Settings</mark>, enters the <mark style="color:blue;">Authentication Source Name</mark> (which becomes part of the SP URLs), and provides IdP settings using **one** of the following modes. The two modes cannot be filled in simultaneously:

| Mode                    | Fields to Fill In                                                                                                                                    | Description                                                                                                                                                                                                                                                        |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| A: Metadata URL         | <mark style="color:blue;">IdP Metadata URL</mark>                                                                                                    | When saved, the system downloads and parses the metadata to obtain the Entity ID, SSO URL, and certificate automatically. The MaiAgent server must be able to reach this URL; settings cannot be saved if it is unreachable or has an invalid format               |
| B: Manual Configuration | <mark style="color:blue;">IdP Entity ID</mark>, <mark style="color:blue;">IdP SSO URL</mark>, <mark style="color:blue;">IdP X.509 Certificate</mark> | All three fields are required. For the certificate, enter the base64 content between `BEGIN CERTIFICATE` and `END CERTIFICATE` in the PEM. Use this mode for IdPs such as Google Workspace that only offer a downloadable metadata file rather than a Metadata URL |

Optional <mark style="color:blue;">Email Domain</mark>: Once configured, members with an email address in this domain are automatically redirected to this SAML login when they enter their email on the login page.

MaiAgent has no field for uploading an IdP Metadata XML file. If you only have a metadata file, extract the Entity ID, SSO URL, and certificate from it and use mode B. There is also no attribute mapping configuration field; see Section 2.2 for the rules.

After saving, the page displays the SP information and the login link for members.

### 5.3 Testing and Validation

After configuration, perform the following tests:

* **First Login Test**: Confirm automatic account creation works correctly
* **Repeat Login Test**: Confirm login uses the existing account
* **Email Case Test**: Verify that emails with different capitalization are correctly identified
* **Logout Test**: Confirm Single Logout (SLO) works correctly

***

## 6. Limitations and Considerations <a href="#limitations" id="limitations"></a>

* **Fixed Attribute Mapping**: Reads only email and display name; mapping cannot be customized, and groups or departments are not read
* **Names Are Not Synchronized**: The display name is written only at first login; later changes at the IdP do not synchronize to MaiAgent
* **Roles Are Not Synchronized**: SAML does not supply roles. To automatically provision members and roles based on IdP groups, use [SCIM or other member provisioning methods](/tech/en/identity-and-access/member-provisioning.md)
* **Deactivation upon Departure**: SSO provisions accounts only at login; disabling a user in the IdP does not disable the MaiAgent member. Use SCIM or the administration interface to deactivate members who leave
* **IdP Certificate Rotation**: Metadata URL mode reads metadata only when settings are saved. After the IdP rotates its signing certificate, return to the settings page and save again (mode A) or update the X.509 certificate field (mode B); otherwise, signature validation fails

***

## 7. Troubleshooting

### 7.1 Common Issues

| Issue                                                              | Possible Cause                                      | Solution                                                                                                                                                                        |
| ------------------------------------------------------------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Unable to Log In**                                               | SAML signature validation failed                    | Check that the IdP certificate has not expired; if the IdP rotated its certificate, save the settings again or update the certificate as described in [Section 6](#limitations) |
| **Duplicate Accounts Created**                                     | Inconsistent email capitalization                   | Ensure the system has applied the email normalization fix                                                                                                                       |
| **Missing Attributes**                                             | The IdP did not send an email attribute             | Login redirects back with `error=email_not_found`; configure the IdP to send any email attribute listed in Section 2.2                                                          |
| **Unable to Log In by Clicking the Application in the IdP Portal** | Login was initiated by the IdP rather than MaiAgent | Set the application's Sign-on URL in the IdP to the MaiAgent login link so MaiAgent initiates login                                                                             |
| **Timestamp Error**                                                | Server clocks are out of sync                       | Ensure the SP and IdP system clocks match (NTP is recommended)                                                                                                                  |

### 7.2 Debugging Tools

* **SAML-tracer**: A browser extension that captures and parses SAML messages
* **MaiAgent Logs**: View detailed SAML processing logs
* **IdP Administration Interface**: Check IdP error logs and user attributes

***

## 8. Related Documentation

* [Organization and Member Management](https://docs.maiagent.ai/org/roles/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
* [SAML Integration](https://docs.maiagent.ai/org/sso/sso-saml) - SAML administration operations and Microsoft Entra ID configuration steps in the user guide
* [Member Provisioning: SCIM / Invitations / SSO](/tech/en/identity-and-access/member-provisioning.md) - Automatic member provisioning and deactivation

### References

* [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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/en/identity-and-access/sso-overview/saml-sso.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
