# idaas-appdev

Part of **IDAAS**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Provision users from external identity provider](../../intent/idaas-provision-idp/SKILL.md). If you're unsure which path to take, check the routing skill first.

# IDaaS User Lifecycle and Synchronization

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Develop and Deploy Application | Synchronous | API reference for developing and deploying applications with IDaaS. |
| Synchronize Accounts via Event Callback | Synchronous | Integrate account synchronization using event callbacks with JWT signature verification. |
| Synchronize User Data with SCIM | Synchronous | Use SCIM 2.0 operations to synchronize user and group data with IDaaS. |

## API Calling Patterns

### Authentication
**Primary method: Bearer Token**

- Include the header: `Authorization: Bearer <your_bearer_token>`
- For SCIM APIs, obtain the Bearer Token via OAuth 2.0 Client Credentials flow from your IDaaS application configuration.
- For event callbacks, authenticate by verifying the JWT signature using the public key from the **Public Key Endpoint** in the IDaaS console (not via Bearer Token in the request header).

> **Note**: Do not send a Bearer Token in event callback requests—IDaaS sends a signed JWT in the request body instead.

### Service Endpoint

- **SCIM 2.0 APIs**: Use the base URL provided in your IDaaS application’s provisioning settings, typically in the format:  
  `https://idaas-dp.aliyuncs.com/scim/v2/{instance_id}`
- **Event Callbacks**: Your application must expose a publicly accessible HTTPS endpoint (e.g., `https://your-app.com/idaas/callback`). The exact URL is configured in the IDaaS console under provisioning settings.
- Common regions: `cn-hangzhou`, `cn-shanghai`, `cn-beijing` (though SCIM endpoints are often global or instance-specific rather than region-bound).

### Synchronous Request Pattern (SCIM & Application APIs)
1. Construct a request with proper `Authorization: Bearer <token>` header.
2. Set `Content-Type: application/scim+json` for write operations (POST, PUT, PATCH).
3. Send the request to the appropriate SCIM endpoint (e.g., `/Users`, `/Groups`).
4. Parse the JSON response immediately—no polling required.

### Event Callback Handling Pattern
1. IDaaS sends a `POST` request to your configured callback URL with a JSON body containing a signed JWT in the `event` field.
2. Retrieve the public key from the **Public Key Endpoint** in IDaaS console.
3. Verify the JWT signature using the public key.
4. If encryption is enabled, decrypt the payload using your private key.
5. Process the user lifecycle event (create, update, delete).
6. Respond within **10 seconds** with a `200 OK` and a JSON body indicating processing results (`successEvents`, `failedEvents`, etc.).
7. Failure to respond in time or returning `4xx/5xx` triggers retries (up to 5 times with backoff: 1s, 5s, 10s, 10s, 10s).

## Parameter Reference

### Synchronize User Data with SCIM

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| filter | string | No | — | max length 1000 chars, must be URL-encoded | Filters results using `eq` and `and` operators (e.g., `userName eq "john"`). |
| startIndex | integer | No | 1 | range 1–1000 | Page number for pagination (1-based). |
| count | integer | No | 20 | range 1–100 | Number of entries per page. Maximum is 100. |
| excludedAttributes | string | No | — | one of: `members` | Excludes specified attributes (e.g., `members` omits group membership list). |

### Synchronize Accounts via Event Callback

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| event | string | Yes | — | — | A signed JSON Web Token (JWT) containing the event payload. Must be verified before processing. |

## Code Examples

### Create a User via SCIM - Shell - All Regions

```bash
curl {baseUrl}/Users \
  --header 'Authorization: Bearer <BearerToken>' \
  --header "content-type:application/scim+json" \
  -X POST \
  -d '{
    "userName": "testuser",
    "displayName": "Test User",
    "emails": [{
      "primary": true,
      "type": "work",
      "value": "test@example.com"
    }],
    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"]
  }'
```

### Get a Specific User - Shell - All Regions

```bash
curl {BaseUrl}/Users/<userId> \
  --header 'Authorization: Bearer <BearerToken>' \
  --header "content-type:application/scim+json" \
  -X GET
```

### List Groups - Shell - All Regions

```bash
curl {BaseUrl}/Groups \
  --header 'Authorization: Bearer <BearerToken>' \
  --header "content-type:application/scim+json" \
  -X GET
```

### Event Callback Request Body Example - JavaScript - China

```javascript
// Sent by IDaaS to your endpoint
{
  "event": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
```

### Successful Event Callback Response - JavaScript - China

```javascript
{
    "successEvents": [
        {
            "eventId": "evt_12345",
            "eventCode": "SUCCESS",
            "eventMessage": "User created successfully"
        }
    ],
    "skippedEvents": [],
    "failedEvents": [],
    "retriedEvents": []
}
```

### Error Response for Invalid Token - JavaScript - China

```javascript
{
    "error": "invalid_token",
    "error_description": "The JWS token is invalid."
}
```

## Response Format

```json
{
    "id": "user_addxxxxxxxxxxxxxxx1",
    "userName": "username1",
    "displayName": "displayName1",
    "active": true,
    "emails": [
        {
            "value": "test1@example.com",
            "type": "work",
            "primary": true
        }
    ],
    "phoneNumbers": [
        {
            "value": "333*****333",
            "type": "work",
            "primary": true
        }
    ],
    "externalId": "externalId1",
    "meta": {
        "resourceType": "User",
        "created": "2025-03-06T03:16:40.201Z",
        "lastModified": "2025-03-06T03:16:40.201Z",
        "location": "{BaseUrl}/Users/user_addxxxxxxxxxxxxxxx1"
    },
    "schemas": [
        "urn:ietf:params:scim:schemas:core:2.0:User"
    ]
}
```

**Key Fields**:
- `id` — Unique identifier assigned by IDaaS
- `userName` — Login name of the user
- `displayName` — Human-readable name
- `emails[].value` — Email address
- `phoneNumbers[].value` — Phone number
- `externalId` — Identifier from your external system
- `meta.created` — Timestamp of creation
- `meta.lastModified` — Timestamp of last update
- `meta.location` — Full URL to retrieve this resource

## Error Handling

| Error Code | Description | Recommended Action |
|-----------|-------------|-------------------|
| invalid_token | The JWS token is invalid. Signature verification failed. | Reject the request, log for debugging, and ensure your public key is up to date. |
| too_many_requests | Your service is busy; IDaaS will throttle and retry. | Reduce processing latency or implement faster response logic. Ensure responses complete within 10 seconds. |
| internal_error | Internal error on your service side. | Investigate server logs; IDaaS will automatically retry up to 5 times. |
| 400 | Bad Request – malformed request or invalid parameters. | Validate SCIM payload structure and parameter values. |
| 401 | Unauthorized – missing or invalid Bearer Token. | Verify token validity and ensure it’s included in the `Authorization` header. |
| 404 | Not Found – user/group ID does not exist. | Confirm the resource ID exists before issuing GET/PUT/PATCH/DELETE. |
| 429 | Too Many Requests – rate limit exceeded. | Implement exponential backoff; respect 100 QPS limit. |
| 500 | Internal Server Error – unexpected server issue. | Retry with backoff; contact support if persistent. |

### Rate Limits & Retry
- **SCIM APIs**: 100 queries per second (QPS) per application instance.
- **Event Callbacks**: Must respond within **10 seconds**. IDaaS retries failed callbacks up to **5 times** with intervals: **1s, 5s, 10s, 10s, 10s**.
- On `429` errors, use exponential backoff and respect the `Retry-After` header if present.

## Environment Requirements
- No specific SDK is required—use standard HTTP clients (e.g., `curl`, `requests`, `fetch`).
- For JWT verification in event callbacks, use a library like `jsonwebtoken` (Node.js), `PyJWT` (Python), or equivalent.
- Store your Bearer Token and private keys securely using environment variables (e.g., `IDaaS_BEARER_TOKEN`).

## FAQ

Q: How do I obtain the Bearer Token for SCIM APIs?
A: In the IDaaS console, navigate to your application’s provisioning settings. The Bearer Token is generated when you configure SCIM-based provisioning using OAuth 2.0 Client Credentials.

Q: What happens if my event callback takes longer than 10 seconds to respond?
A: IDaaS treats it as a failure and schedules a retry. After 5 failed attempts, the event may be marked as permanently failed unless manually retried.

Q: Can I use SCIM to sync groups as well as users?
A: Yes. IDaaS supports full SCIM 2.0 for both `/Users` and `/Groups` endpoints, including create, read, update, patch, and delete operations.

Q: Is the event callback payload encrypted?
A: Optionally. You can enable encryption in the IDaaS console. If enabled, the JWT payload is encrypted, and you must decrypt it using your private key after signature verification.

Q: Are there free quotas for SCIM API usage?
A: Yes—10,000 SCIM API calls per month are free. Beyond that, usage is billed per request.

## Pricing & Billing

### Billing Model
Per-request pricing for SCIM API calls. Event callback processing is included in the IDaaS service tier at no additional cost.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| SCIM API calls | ¥0.001 per call | ¥0.001 per call |

### Free Tier
10,000 SCIM API calls per month free of charge.

### Usage Limits
- 100 QPS per application instance
- Maximum 100 records per SCIM request
- Event callbacks must respond within 10 seconds

### Billing Notes
Billing applies only to SCIM API calls beyond the free tier. Charges are ¥1 per 1,000 calls. Event callback retries do not incur additional costs.