# idaas-auth

Part of **IDAAS**

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

> 💡 **Path Selection**: This skill is one implementation path for [Configure user authentication methods](../../intent/idaas-configure-authentication/SKILL.md). If you're unsure which path to take, check the routing skill first.

# IDaaS Authentication

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Authenticate User | Synchronous | Authenticate users, register new users, verify 2FA codes, recover passwords, and handle social logins. |
| Acquire Access Token | Synchronous | Acquire access tokens for authorized applications. |
| Manage Authentication Tokens | Synchronous | Create, validate, and revoke authentication tokens. |
| Generate WebAuthn Registration URL | Synchronous | Generate a URL for registering WebAuthn authenticators. |

## API Calling Patterns

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

- Use the header: `Authorization: Bearer <your_api_key>`
- Set the environment variable: `DASHSCOPE_API_KEY` for your API key
- Some endpoints may use application-level credentials (`client_id`/`client_secret`) instead of user API keys

### Service Endpoint
The APIs use region-specific endpoints with the pattern: `https://{product}.{region}.aliyuncs.com`

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

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

### Synchronous API Pattern
All authentication APIs in this domain follow a synchronous calling pattern:

1. Make a direct HTTP request to the endpoint with required parameters
2. Receive an immediate JSON response with results or error information
3. Handle the response based on the status and data returned

No polling or async task handling is required since all operations complete immediately.

## Parameter Reference

### Authenticate User

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| fId | String | false | null | null | Process ID from previous flow; used to continue authentication or registration flows. |
| username | String | true | null | null | User's username for login. |
| password | String | true | null | null | User's password for login. |
| response_type | String | false | null | one of: code, Token | Specifies whether to return an auth code ('code') or access token ('Token'). |
| agreeConsent | Boolean | false | null | null | Indicates if the user agrees to terms and conditions. |
| captchaCode | String | false | null | null | Unique identifier of the image CAPTCHA obtained from the captcha API. |
| captchaText | String | false | null | null | Text input from the user based on the displayed CAPTCHA image. |
| phoneNumber | String | false | null | null | Mobile number for SMS-based authentication or registration. |
| phoneRegion | String | false | 86 | null | Area code for mobile number (default: 86). |
| email | String | false | null | null | Email address for email-based authentication or registration. |
| type | String | true | null | one of: SMS, EMAIL | Type of verification method: SMS or EMAIL. |
| code | String | true | null | null | Verification code sent via SMS or email. |
| enterpriseAuthId | String | true | null | null | ID of the social authentication source (e.g., WeChat, Alipay). |
| state | String | false | null | null | State parameter returned by third-party OAuth provider. If redirecting to non-default app, format as `ID:{idaasAppId}`. |
| loginCode | String | true | null | null | Temporary login code from WeChat `wx.login`. |
| encryptedData | String | true | null | null | Encrypted user data from WeChat `getUserProfile` or `getPhoneNumber`. |
| iv | String | true | null | null | Initialization vector for decryption of encrypted data. |
| deviceId | String | false | null | null | Optional device ID for tracking. |
| userType | String | false | regular | null | Custom user type code (e.g., doctor, default). |
| newPassword | String | true | null | null | New password set during password recovery. |
| applicationExternalId | String | true | null | null | Application ID created in security auth. |
| mobileExtendParamsJson | String | true | null | null | JSON string containing mobile end information. |
| mobileExtendParamsJsonSign | String | true | null | null | Signature of the mobile extend params JSON. |
| gestureSign | String | true | null | null | Encrypted gesture using username. |
| idToken | String | true | null | null | Token issued during initial authentication. |

### Acquire Access Token

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| client_id | string | true | null | null | Your appKey from IDaaS |
| client_secret | string | true | null | null | Your appSecret from IDaaS |
| grant_type | string | true | null | one of: client_credentials, authorization_code, refresh_token, implicit, password | Fixed value: client_credentials, authorization_code, refresh_token, implicit, password |
| scope | string | false | null | space-separated values from: APPLICATION_API, MANAGEMENT_APPLICATION_API, USER_API, openid, profile, email, phone, read | Use APPLICATION_API for regular application APIs, or MANAGEMENT_APPLICATION_API for management APIs. Must include USER_API for user-context flows. |
| code | string | true | null | null | Authorization code received at the callback URL |
| redirect_uri | string | true | null | URL-encoded | Callback URL registered in the IDaaS application settings |
| refresh_token | string | true | null | null | The user's refresh token |
| idaasAppId | string | true | null | null | Application ID from the IDaaS console Application Management list |

### Manage Authentication Tokens

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| action | string | true | null | one of: create, validate, revoke | The operation to perform on the token. Valid values: create, validate, revoke. |
| token_id | string | false | null | max length 64 characters | The unique identifier of the token to be validated or revoked. |
| user_id | string | false | null | max length 128 characters | The ID of the user associated with the token. Required when creating a new token. |
| expires_in | integer | false | 3600 | range 300-31536000 | The duration in seconds for which the token will be valid after creation. |
| instanceId | string | true | null | null | Instance ID. |
| consumerId | string | true | null | null | Consumer ID of the authentication token. |
| credentialProviderIdentifier | string | true | null | null | Credential provider identifier. |
| token | string | true | null | null | The original authentication token. Pass either the original authentication token or a derived short token. |
| token_type_hint | string | false | null | null | A hint about the type of the authentication token. No value is currently required for this parameter. |

### Generate WebAuthn Registration URL

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| InstanceId | string | true | null | null | The instance ID. |
| UserId | string | true | null | null | The user ID. |
| DomainId | string | false | null | null | The domain ID. |

## Code Examples

### Password Login - Python - all

```python
import requests

# Example: Password Login
url = "https://api.idaas.com/api/bff/v1.2/developer/ciam/login/pwd"
headers = {"Content-Type": "application/json"}
body = {
    "username": "testuser",
    "password": "securepass",
    "response_type": "Token"
}

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

### Send Verification Code - JavaScript - all

```javascript
const axios = require('axios');

// Example: Send Verification Code
const url = 'https://api.idaas.com/api/bff/v1.2/developer/ciam/register/obtain_code';
const data = {
    fId: 'abc123',
    type: 'SMS',
    phoneNumber: '15100001234'
};

axios.post(url, data, {
    headers: { 'Content-Type': 'application/json' }
})
.then(res => console.log(res.data))
.catch(err => console.error(err.response.data));
```

### Social Login - Bash - all

```bash
curl -X POST https://api.idaas.com/api/bff/v1.2/developer/ciam/login/social \
  -H "Content-Type: application/json" \
  -d '{
    "enterpriseAuthId": "ciammasterwechat",
    "code": "011RaA1w3Gp0GY234r0w3vhlzU2RaA1P",
    "state": "xxxxx",
    "agreeConsent": true
  }'
```

### Client Credentials Token - Bash - all

```bash
curl --request POST \
  --url 'https://<your-domain>/api/bff/v1.2/developer/ciam/oauth/token' \
  --header 'Content-Type: application/json' \
  --data '{
    "client_id": "<your-appKey>",
    "client_secret": "<your-appSecret>",
    "grant_type": "client_credentials",
    "scope": "APPLICATION_API"
  }'
```

### Create Authentication Token - Python - all

```python
import requests

def create_token(user_id, expires_in=3600):
    url = "https://api.idaas.example.com/v1/tokens"
    headers = {
        "Authorization": "Bearer $DASHSCOPE_API_KEY",
        "Content-Type": "application/json"
    }
    payload = {
        "action": "create",
        "user_id": user_id,
        "expires_in": expires_in
    }
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# Example usage
result = create_token("u12345", 7200)
print(result)
```

### Revoke Authentication Token - Bash - all

```bash
curl -X POST https://eiam-api.aliyuncs.com/v2/idaas_ue2jvisn35ea5lmthk267xxxxx/authenticationTokens/_/actions/revokeByConsumer \
-H "Authorization: Bearer xxxxxx" \
-H "Content-Type: application/json" \
-d '{"consumerId": "test_jwt_subject", "credentialProviderIdentifier": "test_example_identifier"}'
```

### Validate Authentication Token - Bash - all

```bash
curl -X POST https://api.aliyun.com/v2/idaas_ue2jvisn35ea5lmthk267xxxxx/authenticationTokens/_/actions/validate \
-H "Content-Type: application/json" \
-d '{"token": "eyJhbGciOixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}'
```

### Generate WebAuthn Registration URL - Python - all

```python
import dashscope

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

# Define the parameters
params = {
    'InstanceId': 'idaas_ue2jvisn35ea5lmthk267xxxxx',
    'UserId': 'user_e2jvisn35ea5lmthk267xx'
}

# Call the API
response = dashscope.call('Eiam/2021-12-01/GenerateWebAuthnAuthenticatorRegistrationUrl', params=params)

# Print the response
print(response)
```

## Response Format

```json
{
  "success": true,
  "code": "Operation.Success",
  "message": "Operation.Success",
  "requestId": "1656326070459$be264b8d-a6ca-a75c-f224-ade8531cc4af",
  "data": {
    "userId": null,
    "uuid": "c0d7ebbae869a76781183310768088543DkolDLzrSB",
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjkxMGJkMTY4MzFhOTdhZDRhYjdlMGRjMmYzNDY5NTJiaXF6UVdEWWZMbz****...",
    "token_type": "bearer",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjkxMGJkMTY4MzFhOTdhZDRhYjdlMGRjMmYzNDY5NTJiaXF6UVdEWWZMbzUifQ...",
    "expires_in": 179999,
    "scope": "USER_API",
    "id_token": "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJjMGQ3ZWJiYWU4NjlhNzY3ODExODMzMTA3NjgwODg1NDNEa29sREx6clNCIiwic2NvcGUiOiJjMGQ3ZWJiYWU4NjlhNzY3ODExODMzMTA3NjgwODg1NDNEa29sREx6clNCIDEyMzQ2MTExMUAxMy5jb20gMTU4MDExMTExMDAiLCJsb2dpbk5hbWUiOiJ0ZXN0MDI3IiwiY3VzdG9tZXJJZCI6IjQ0MTIxNjU2Mjk4NDE5NTY4MTkiLCJleHAiOjE2NTY1MDYwODAsImp0aSI6InZRN0Uxa0xPTzVpQ3ZuR2JYTUdkZWciLCJpYXQiOjE2NTYzMjYwODEsIm5iZiI6MTY1NjMyNjAyMX0.CW3d41c7oGP23FU5DKGyiX553qLea09oYS4s-dISnse9iE-gGjZxUEqXlHSgfSERES9VeaaVwXEUqPOGKkHEEW0fQKcS82WTepiy1QHB0WeRzqKQQY9t38Rp-v_uMlpKLhnrfK_q_Q1A9ak5kDlpvidp2p5I84NmnisiQmGW7ep3xzs9V7axV9ump207ek5Bl1fs1kZ2gOUTHyWuQ0XoIDF6NHmUjtpA31jc5a13o-UIgX1Bd3ZNjmFiwm4EQ3xyZci72w0rTV7EyRa4KU7KyBjv-QJGv8T2Y4e2GnI-BiqWsaE1wtImhvXRRQ__MT_lRDph87-7zA4cTWEsZJRSXg"
  }
}
```

**Key Fields**:
- `data.access_token` — The access token for API authorization
- `data.refresh_token` — Token used to obtain new access tokens
- `data.id_token` — Identity token containing user information
- `data.expires_in` — Token expiration time in seconds
- `data.uuid` — Unique user identifier
- `data.userId` — User ID from the system
- `data.fId` — Flow/process ID for continuing authentication flows
- `data.flowType` — Type of authentication flow being executed
- `data.phoneNumber` — Phone number associated with the user

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|-------------------|
| Operation.Success | Request succeeded. | No action needed. |
| Operation.Failure | General failure. Check request parameters and retry. | Verify all parameters and retry the request. |
| Operation.Failure.User.Not.Exist | User does not exist. Proceed with registration or check credentials. | Register the user first or verify the username. |
| Operation.Failure.Social.Login | Social login failed. Verify the auth code and state. | Check the social auth code and state parameter. |
| Operation.Failure.Unsupport.2fa.Type | Unsupported 2FA type. Check supported methods in config. | Use a supported 2FA method from configuration. |
| Operation.Failure.User.Password.Error | Incorrect password. Retry with correct credentials. | Verify and re-enter the correct password. |
| Operation.Failure.No.User.Bind | No account bound in security auth. Bind account first. | Complete account binding before proceeding. |
| Operation.Failure.IDaaS.NoUser | No account bound in CIAM. Create or link account. | Create or link a CIAM account first. |
| Operation.Failure.Service.Internal.Error | Internal service error. Retry later or contact support. | Wait and retry, or contact support if persistent. |
| Operation.Failure.Gesture.Error | Incorrect gesture. Try again or reset gesture. | Re-enter the gesture or reset it. |
| Params.Blank | One or more required parameters are missing. Check request body. | Ensure all required parameters are provided. |
| Params.Illegal | Invalid parameter value. Check format and constraints. | Verify parameter formats and constraints. |
| invalid_client | The application does not exist or has been disabled. Verify the idaasAppId and ensure the application is active. | Check that the application exists and is enabled in the console. |
| 400 | Bad Request: Invalid or missing required parameters. | Validate all required parameters are present and correctly formatted. |
| 401 | Unauthorized: Invalid or expired authentication token provided. | Use a valid, non-expired authentication token. |
| 403 | Forbidden: The user does not have sufficient privileges to revoke the token, even if the token is valid. | Ensure the user has proper permissions for token management. |
| 404 | Not Found: The specified token_id does not exist. | Verify the token_id exists before attempting operations. |
| 429 | Too Many Requests: Rate limit exceeded. Wait before retrying. | Implement exponential backoff and retry after waiting. |
| 500 | Internal Server Error: An unexpected error occurred on the server side. | Contact support if the issue persists. |
| InvalidParameter | One or more parameters are invalid. Check that InstanceId, UserId, and DomainId (if provided) are correctly formatted. | Verify parameter formats and values. |
| Unauthorized | The request is not authorized. Ensure valid credentials and proper permissions are configured. | Check credentials and permissions configuration. |
| ResourceNotFound | The specified instance or user does not exist. Verify the InstanceId and UserId values. | Confirm the instance and user IDs exist. |
| Throttling | Too many requests have been made. Reduce the request rate or implement exponential backoff. | Reduce request frequency or implement backoff strategy. |

### Rate Limits & Retry
- Standard rate limits: 100 QPS per app/account
- Free tier: 1000 requests per month
- When encountering 429 errors, implement exponential backoff with jitter
- Retry after the duration specified in the `Retry-After` header if present

## Requirements

- SDK package: `dashscope>=1.14.0` (for WebAuthn and token management APIs)
- Environment variable setup: `export DASHSCOPE_API_KEY=your_api_key`
- For OAuth token acquisition, you need `client_id` and `client_secret` from the IDaaS console

## FAQ

Q: How do I authenticate API requests?
A: Use Bearer Token authentication with the header `Authorization: Bearer <your_api_key>`. Set your API key in the `DASHSCOPE_API_KEY` environment variable.

Q: What's the difference between access_token, id_token, and refresh_token?
A: `access_token` is used to authorize API requests, `id_token` contains user identity information in JWT format, and `refresh_token` is used to obtain new access tokens when they expire.

Q: How do I handle 2FA verification in my application?
A: First call the appropriate endpoint to trigger 2FA (SMS/email/TOTP), then use the `verify_second_factor` endpoint with the code received by the user to complete authentication.

Q: Can I use social login with WeChat mini-programs?
A: Yes, use the `/login/miniprogram/silent`, `/login/miniprogram/authorized`, or `/login/miniprogram/phone` endpoints with the appropriate WeChat parameters like `loginCode`, `encryptedData`, and `iv`.

Q: What regions are supported for these APIs?
A: Common regions include `cn-hangzhou`, `cn-shanghai`, and `cn-beijing`. For international deployments, use `api.alibabacloud.com` instead of `api.aliyuncs.com`.

## Pricing & Billing

### Billing Model
Per-request billing model for most authentication operations. Token issuance via OAuth is free within standard limits.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| standard | 0.001 / | 0.001 / |
| default | 0.0001 / | 0.0001 / |

### Free Tier
Monthly 1000 free requests for authentication operations and token management APIs.

### Usage Limits
- 100 QPS per app/account
- Free tier: 1000 requests/month
- Single request maximum 8192 characters for WebAuthn API

### Billing Notes
All authentication operations are billed per request regardless of success or failure. Async tasks are not applicable since all APIs are synchronous. Token revocation does not incur additional costs beyond the initial request.