# idaas-access

Part of **IDAAS**

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

> 💡 **Path Selection**: This skill is one implementation path for the following routing skills. If you're unsure which path to take, check the corresponding routing skill:

> - [Set up secure machine-to-machine (M2M) access](../../intent/idaas-secure-access/SKILL.md)
> - [Integrate SSO for an application](../../intent/idaas-integrate-application/SKILL.md)

# IDaaS Access Control

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|--------|----------|------|
| Manage Authorization Resources | Synchronous | Creates and deletes authorization resources used in access control policies. |
| Manage Authorization Rules | Synchronous | Creates, updates, deletes, enables/disables authorization rules and manages attachments to users, groups, and applications. |
| Manage Domains | Synchronous | Creates, deletes, enables/disables custom domains and manages domain proxy tokens. |
| Manage Resource Server Authorizations | Synchronous | Authorizes and revokes resource servers and their scopes for clients, groups, organizational units, and users. |
| List User Groups | Synchronous | Retrieves the list of groups that a specific user belongs to. |
| Generate OAuth Tokens | Synchronous | Generates OAuth 2.0 access tokens for applications and users. |
| Manage JWT Tokens | Synchronous | Generates, obtains, and validates JWT authentication tokens. |
| Manage M2M Client Tokens | Synchronous | Obtains and manages machine-to-machine client access tokens. |
| Generate Device Codes | Synchronous | Generates device codes for device authorization flows. |
| Manage User Access | Synchronous | Unlocks user accounts and updates organizational unit descriptions. |
| Manage Password Configurations | Synchronous | Retrieves and sets password complexity, history, and initialization configurations. |
| Use Token Exchange to Delegate Access Across Services | Synchronous | Exchanges tokens to delegate access between different services securely. |
| Permissions for Alibaba Cloud Applications | Synchronous | Manages permissions and access for Alibaba Cloud service applications within IDaaS. |

## API Calling Mode

### Authentication
The primary authentication method is Bearer Token authentication.

- **Header format**: `Authorization: Bearer <your_api_key>`
- **Environment variable**: `DASHSCOPE_API_KEY`
- While other authentication methods may exist, Bearer Token is the recommended approach for all IDaaS Access Control API calls.

### Service Endpoint
The APIs use region-specific endpoints with the following pattern:

`https://eiam.api.alibabacloud.com/2021-12-01/{API_NAME}`

Common regions include:
- cn-hangzhou
- cn-shanghai  
- cn-beijing

For international regions, use `api.alibabacloud.com` instead of `api.aliyun.com`.

### Synchronous API Pattern
All IDaaS Access Control APIs follow a synchronous calling pattern:

1. **Make a direct HTTP request** to the API endpoint with required parameters in the request body (for POST) or query parameters (for GET)
2. **Include the Authorization header** with your Bearer token
3. **Receive an immediate JSON response** containing either the requested data or error information
4. **Handle the response** by checking the status code and parsing the JSON body

For POST requests, include `Content-Type: application/json` header and send parameters as JSON in the request body. For GET requests, pass parameters as URL query parameters.

## Parameter Reference

### Manage Authorization Resources

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| InstanceId | string | true | | | The instance ID. |
| AuthorizationRuleId | string | true | | | The authorization rule ID. |
| AuthorizationResourceEntityType | string | true | | one of: cloud_account_role | The type of the resource entity associated with the authorization resource. Valid values: cloud_account_role (a cloud role). |
| AuthorizationResourceEntityId | string | true | | | The ID of the resource entity associated with the authorization resource. |
| ClientToken | string | true | | max length 64 characters, ASCII only | A client token that ensures the idempotence of the request. Generate a unique value from your client. The token can contain only ASCII characters and must not exceed 64 characters. |

### Manage Authorization Rules

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| InstanceId | string | true | | | The instance ID. |
| AuthorizationRuleName | string | true | | max 64 characters | The name of the authorization rule. The name can be up to 64 characters in length. |
| ProjectId | string | true | iprj_system_default | | The ID of the project to associate with the authorization rule. If you are unsure which project to use, specify the default project iprj_system_default. |
| AuthorizationResourceScope | string | false | global | one of: global, custom | The scope of authorized resources. Valid values: global (all resources within the project), custom (specified resources within the project). |
| Description | string | false | | max 128 characters | The description of the authorization rule. The description can be up to 128 characters in length. |
| ClientToken | string | true | | ASCII only, max 64 characters | A unique token that you provide to ensure the idempotence of the request. The token can contain only ASCII characters and cannot exceed 64 characters in length. |

### Generate OAuth Tokens

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| instanceId | string | true | | | The instance ID. |
| applicationId | string | true | | | The application ID. |
| grant_type | string | true | | one of: client_credentials, refresh_token, authorization_code, urn:ietf:params:oauth:grant-type:device_code, password | The authorization grant type. |
| client_id | string | false | | | The client ID. |
| client_secret | string | false | | | The client secret. This parameter is required when `grant_type` is `client_credentials` and the `client_secret_post` method is used. |
| scope | string | false | | one of: openid, email, phone, profile | The scope. This parameter is optional. Multiple values are supported. Separate multiple values with spaces. Valid values: openid, email, phone, profile. |

### Manage JWT Tokens

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| instanceId | string | true | | | Instance ID. |
| Authorization | string | true | | | Authentication information. Format: Bearer ${access_token}. Enter the Access Token issued by IDaaS. |
| credentialProviderIdentifier | string | true | | | Credential provider identity. |
| subject | string | true | | | The `sub` field of the JWT. |
| audiences | array | true | | | The `aud` field of the JWT. |
| expiration | integer | false | | | The validity period of the JWT, in seconds. |
| includeDerivedShortToken | boolean | false | | | Whether the generated JWT needs to include a "derived short token". |

### Manage M2M Client Tokens

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| client_id | string | true | | max length 256 characters | The unique identifier for the M2M client application. |
| client_secret | string | true | | max length 512 characters | The secret key associated with the client ID. |
| grant_type | string | true | | one of: client_credentials | The type of grant being requested. For M2M, this must be 'client_credentials'. |

### Use Token Exchange to Delegate Access Across Services

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| grant_type | String | true | | | Must be urn:ietf:params:oauth:grant-type:token-exchange. |
| subject_token | String | true | | | The access token that represents the end-user identity. |
| subject_token_type | String | true | | | Must be urn:ietf:params:oauth:token-type:access_token. |
| requested_token_type | String | false | urn:ietf:params:oauth:token-type:access_token | | The type of token to issue. Defaults to urn:ietf:params:oauth:token-type:access_token. |
| scope | String | true | | | Permissions for the new token. Format: <audience>|<scope>. |
| audience | String | false | | | Logical name of the target service. Must match the audience portion of scope. |
| client_id | String | true | | | The OAuth client ID of the calling application. |
| client_secret | String | true | | | The OAuth client secret of the calling application. |

## Code Examples

### Create Authorization Resource - Python - all

```python
import requests

url = "https://eiam.api.alibabacloud.com/2021-12-01/CreateAuthorizationResource"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_ACCESS_TOKEN"
}
params = {
    "InstanceId": "idaas_ue2jvisn35ea5lmthk267xxxxx",
    "AuthorizationRuleId": "arrule_01kf143ug06fg7m9f43u7vahxxxx",
    "AuthorizationResourceEntityType": "cloud_account_role",
    "AuthorizationResourceEntityId": "carole_01kmek49aqxxxx",
    "ClientToken": "client-token-example"
}

response = requests.post(url, json=params, headers=headers)
print(response.json())
```

### Delete Authorization Rule - curl - all

```bash
curl -X POST https://eiam.api.alibabacloud.com/2021-12-01/DeleteAuthorizationRule \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer $DASHSCOPE_API_KEY' \
-d '{"InstanceId":"idaas_ue2jvisn35ea5lmthk267xxxxx","AuthorizationRuleId":"arrule_01kf143ug06fg7m9f43u7vahxxxx"}'
```

### List Authorization Rules For User - Python - all

```python
import requests

url = "https://eiam.api.alibabacloud.com/2021-12-01/ListAuthorizationRulesForUser"
headers = {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "Content-Type": "application/json"
}
params = {
    "InstanceId": "idaas_ue2jvisn35ea5lmthk267xxxxx",
    "UserId": "user_d6sbsuumeta4h66ec3il7yxxxx"
}

response = requests.get(url, headers=headers, params=params)
print(response.json())
```

### Generate OAuth Token - curl - all

```bash
curl -X POST https://api.alibabacloud.com/api/Eiam/2021-12-01/GenerateOauthToken \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-d '{
  "InstanceId": "idaas_ue2jvisn35ea5lmthk267xxxxx",
  "ApplicationId": "app_mkv7rgt4d7i4u7zqtzev2mxxxx",
  "ScopeValues": ["User:Read:ALL"],
  "Audience": "https://example.com"
}'
```

### Generate JWT Authentication Token - bash - all

```bash
curl -X POST https://api.aliyun.com/v2/idaas_ue2jvisn35ea5lmthk267xxxxx/authenticationTokens/_/actions/generateJwt \
-H "Authorization: Bearer xxxxxx" \
-H "Content-Type: application/json" \
-d '{
  "credentialProviderIdentifier": "test_example_identifier",
  "issuer": "https://test.issuer.com",
  "subject": "test_jwt_subject",
  "audiences": ["test_jwt_audience"],
  "customClaims": {},
  "expiration": 900,
  "includeDerivedShortToken": true
}'
```

### Get M2M Client Token - curl - all

```bash
curl -X POST https://api.idaas.example.com/v1/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=my-client-id&client_secret=my-client-secret&grant_type=client_credentials"
```

### Exchange Token for Delegated Access - bash - all

```bash
curl -X POST 'https://{domain}/api/v2/iauths_system/oauth2/token' \
  --data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
  --data-urlencode 'subject_token=<subject_token>' \
  --data-urlencode 'subject_token_type=urn:ietf:params:oauth:token-type:access_token' \
  --data-urlencode 'requested_token_type=urn:ietf:params:oauth:token-type:access_token' \
  --data-urlencode 'scope=mcp-server|user:read' \
  --data-urlencode 'audience=mcp-server' \
  --data-urlencode 'client_id=<client_id>' \
  --data-urlencode 'client_secret=<client_secret>'
```

### Unlock User Account - Python - all

```python
import dashscope

# Set your API key
dashscope.api_key = 'your-api-key'

# Call the UnlockUser API
response = dashscope.api_call(
    method='POST',
    url='https://eiam.aliyuncs.com/api/v1/UnlockUser',
    data={
        'InstanceId': 'idaas_ue2jvisn35ea5lmthk267xxxxx',
        'UserId': 'user_d6sbsuumeta4h66ec3il7yxxxx'
    }
)

print(response)
```

## Response Format

```json
{
  "RequestId": "0441BD79-92F3-53AA-8657-F8CE4A2B912A",
  "AuthorizationResourceId": "arres_01kgh3jvt7pk093rv6giu0c0qxxxx"
}
```

**Key Fields**:
- `RequestId` — Unique identifier for the API request, useful for troubleshooting
- `AuthorizationResourceId` — The ID of the created authorization resource

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|---------------|--------------------|-----------------------------|
| 400 | Invalid parameter provided. Check the request parameters and ensure they are correctly formatted. | Validate all request parameters against the API specification and correct any formatting issues. |
| 403 | Access denied. Ensure the calling identity has sufficient permissions to perform this operation. | Verify that your account or role has the necessary RAM permissions for the requested operation. |
| 429 | Too many requests. Rate limiting is in effect. Retry after a delay or reduce the request frequency. | Implement exponential backoff and respect rate limits; consider caching responses where appropriate. |
| 500 | Internal server error. Contact technical support for assistance. | Retry the request after a short delay; if the issue persists, contact Alibaba Cloud support with the RequestId. |
| 404 | The specified EIAM instance or authorization rule does not exist. Verify the IDs are correct. | Double-check the InstanceId and AuthorizationRuleId values against your IDaaS console. |
| 409 | The authorization rule is still enabled. Disable the rule before attempting deletion. | First call DisableAuthorizationRule, then retry the deletion operation. |

### Rate Limits & Retry
Rate limits vary by API but commonly include 100 QPS per account. When encountering 429 errors:

- Implement exponential backoff with jitter
- Respect the Retry-After header if present
- Consider batching operations where possible to reduce request volume

## Environment Requirements

- **SDK**: `dashscope>=1.14.0` (for certain APIs)
- **Environment variable setup**: `export DASHSCOPE_API_KEY=your_key`
- **Python version**: Compatible with standard Python HTTP libraries (requests)

## FAQ

Q: How do I handle idempotency for create operations?
A: Use the ClientToken parameter with a unique value for each request. This ensures that duplicate requests don't create multiple resources. The token must be ASCII-only and no more than 64 characters.

Q: What's the difference between authorization rules and authorization resources?
A: Authorization rules define the access control policy (who can access what), while authorization resources represent the actual entities (like cloud roles) that are granted access through those rules.

Q: How do I authenticate API calls?
A: Use Bearer Token authentication by setting the Authorization header to "Bearer YOUR_ACCESS_TOKEN" where YOUR_ACCESS_TOKEN is your DASHSCOPE_API_KEY.

Q: Can I use the same token for multiple API calls?
A: Yes, the same access token can be used across different IDaaS Access Control APIs as long as it has the necessary permissions and hasn't expired.

Q: What should I do if I get a 403 Forbidden error?
A: Verify that your RAM user or role has the required permissions for the specific API operation. Check the RAM policy attached to your identity and ensure it includes the necessary eiam:* actions.

## Pricing & Billing

### Billing Model
Per-request billing model where each API call counts as one request regardless of success or failure.

### Price Reference

| Tier/Model | Input Price | Output Price | Other Fees |
|-----------|---------|---------|---------|
| standard | 0.0001 / | 0.0001 / |
| default | 0.001 / | 0.001 / |

### Free Tier
Monthly free quotas ranging from 1,000 to 10,000 free calls depending on the specific API operation.

### Usage Limits
Common rate limits include 100 QPS per account, with some APIs having lower limits of 10 QPS.

### Billing Notes
- Each successful API call counts as one request
- Idempotent calls with the same ClientToken are not charged multiple times
- Free tier resets monthly
- Failed requests may still be counted toward quotas and billing depending on the specific API