---
url: /en/paas/platform-token.md
description: >-
  Documents the Platform Token API for PAAS deployments, enabling third-party
  services to exchange JWT-signed tokens for temporary CNB OpenAPI access tokens
  by username, user ID, OpenID, repository, or organization.
---
## Overview

The Platform Token allows third-party services to obtain temporary access tokens
for the `Cloud Native Build` OpenAPI via the token exchange interface.

## Platform Token Application

Go to the Admin Management Platform to create a Platform Token for third-party services,
which provides the **name** and **secret\_key**.

## Service Address

The service request address is `3rd.cnbprod.alpha.qq.com`.

## API

CNB provides the following token exchange interfaces:

### Token Exchange by Username

* API Address: `/platform-token/-/user/{username}`
* Method: "POST"
* SystemScope: system-token:rw
* Description: Exchanges a personal token for the specified {username} user.
* Parameters:
  * expire: Optional parameter, token validity period, supports 1m~24h

### Token Exchange by User ID

* API Address: `/platform-token/-/userid/{userid}`
* Method: "POST"
* SystemScope: system-token:rw
* Description: Exchanges a personal token for the specified {userid} user.
* Parameters:
  * expire: Optional parameter, token validity period, supports 1m~24h

### Token Exchange by OpenID

* API Address: `/platform-token/-/openid/{openid}`
* Method: "POST"
* SystemScope: system-token:rw
* Description: Exchanges a personal token for the specified `{openid}` user.
* Parameters:
  * user\_type: Optional parameter. User type mapping:
    * `0`: WeChat user
    * `1`: OAuth user
    * `2`: Test user
    * `3`: Assistant user
    * `4`: IOA authorized user\
      Default is `1`.
  * expire: Optional parameter. Token validity period, supports 1m~24h

### Token Exchange by Repository Path

* API Address: `/platform-token/-/repo/{repo-path}`
* Method: "POST"
* SystemScope: system-token:rw
* Description:
  This interface randomly selects a responsible user from the `{repo-path}` repository and exchanges a personal token for
  that user.
* Parameters:
  * expire: Optional parameter, token validity period, supports 1m~24h

### Token Exchange by Organization Path

* API Address: `/platform-token/-/organization/{organization-path}`
* Method: "POST"
* SystemScope: system-token:rw
* Description:
  This interface randomly selects a responsible user from the `{organization-path}` organization and exchanges a personal
  token for that user.
* Parameters:
  * expire: Optional parameter, token validity period, supports 1m~24h

### List All Root Organizations

* API Address: `/platform-token/-/organization`
* Method: "GET"
* SystemScope: system-search:r
* Description: Traverse and list all root organization information.
* Parameters:
  * page: Page number, starting from 1
  * page\_size: Number of items per page
  * search: Root organization name, supports exact match only

### Resolve Object Information by Resource ID

* API Address: `/platform-token/-/resolve/{type:string}`
* Method: "POST"
* SystemScope: system-search:r
* Description: Resolve object information by resource ID.
* Parameters:
  * type: Type (organization/repo/mission/registry/user)
  * body: Request ID list

    ```json
    {
      "id": ["123"]
    }
    ```

### List Active Repositories

* API Address: `/platform-token/-/active-repos`
* Method: "GET"
* SystemScope: system-search:r
* Description: List the repositories that had activity within the specified 10-minute time segment,
  so that third-party services can pull repository changes incrementally.
* Parameters (all time parameters are calculated in the UTC+8 time zone):
  * date: Optional parameter, date in yyyyMMdd format, defaults to today
  * hour: Optional parameter, hour, ranges from 0 to 23, defaults to the current hour
  * segment: Optional parameter, 10-minute segment number, ranges from 0 to 5,
    defaults to the current segment. Each hour is divided into 6 segments, where `0` means
    minutes 0-9, `1` means minutes 10-19, and so on
* Response: List of active repositories. An empty array is returned when there is no activity in the segment.

  ```json
  [
    {
      "repo_id": "1293243433212",
      "slug": "organization/repo"
    }
  ]
  ```

:::: warning Note
Active repository data is retained for **24 hours** only. Pull it within 24 hours,
otherwise the segment returns an empty array. Polling every 10 minutes is recommended
so that no segment is missed.
::::

### Resolve Object Information by Binding Code or Phone Number

* API Address: `/platform-token/-/bind/user`
* Method: "POST"
* SystemScope: system-bind:r
* Description: Resolve object information by binding code or authenticated phone number.
* Parameters:
  * body: Request JSON content

    ```json
    {
      "type": "code",
      "user": "someone",
      "code": "123456"
    }
    ```

    * type: Code type, supports `code` (binding code) or `phone` (phone number)
    * code: Code content, e.g., 123456 or 1581xxx
    * user: CNB account username
* Response: User information

  ```json
  {
    "id": "1293243433212",
    "username": "someone"
  }
  ```

### Bind User

* API Address: `/platform-token/-/bind/user/{openid:string}`
* Method: "POST"
* SystemScope: system-bind:rw
* Description: Bind a user.
* Parameters:
  * openid: Unique ID of the third-party platform user
  * body: Request JSON content

    ```json
    {
      "type": "code",
      "code": "123456",
      "user": "someone",
      "metadata": {
        "name": "hello"
      }
    }
    ```

    * type: Code type, supports `code` (binding code) or `phone` (phone number)
    * code: Code content, e.g., 123456 or 1581xxx
    * user: CNB account username
    * metadata: Custom metadata
* Response: User information

  ```json
  {
    "id": "1293243433212",
    "username": "someone"
  }
  ```

### Batch Unbind Users

* API Address: `/platform-token/-/unbind/user/{username:string or userid:string}`
* Method: "POST"
* SystemScope: system-bind:rw
* Description: Unbind all binding records of the user on this platform.

### Unbind User

* API Address: `/platform-token/-/unbind/user/{username:string or userid:string}/{openid:string}`
* Method: "POST"
* SystemScope: system-bind:rw
* Description: Unbind a specific binding record of the user on this platform.

### Lock User

* API Address: `/platform-token/-/lock/user/{username:string}`
* Method: "POST"
* SystemScope: system-lock:rw
* Description: Lock the specified `{username}` user
* Parameters:
  * body: Request JSON content

    ```json
    {
      "lock_duration": "10"
    }
    ```

    * lock\_duration: Lock duration in days

### Unlock User

* API Address: `/platform-token/-/unlock/user/{username:string}`
* Method: "POST"
* SystemScope: system-lock:rw
* Description: Unlock the specified `{username}` user

### Create New User

* API Address: `/platform-token/-/user/create/{openid:string}`
* Method: "POST"
* SystemScope: system-user:rw
* Description: Create a new CNB user with specified `{openid}`
* Parameters:
  * body: Request JSON content

    ```json
    {
      "name": "someone",
      "nick": "someone",
      "email": "someone@cnb.com"
    }
    ```

    * name: Username
    * nick: User nickname
    * email: User email

### Update User Information

* API Address: `/platform-token/-/user/update/{openid:string}`
* Method: "POST"
* SystemScope: system-user:rw
* Description: Update information for the specified `{openid}` CNB user
* Parameters:
  * body: Request JSON content

    ```json
    {
      "name": "someone",
      "nick": "someone",
      "email": "someone@cnb.com"
    }
    ```

    * name: Username
    * nick: User nickname
    * email: User email

### Query User Information by Email

* API Address: `/platform-token/-/user`
* Method: "POST"
* SystemScope: system-userinfo:r
* Description: Query user information based on email addresses
* Parameters:
  * body: Request email list

    ```json
    {
      "emails": ["test1@tencent.com", "test2@tencent.com"]
    }
    ```

Choose the appropriate API based on your needs.

## Header Information

* `Authorization`, string type, standard HTTP authentication header field,
  using standard JWT for signature calculation. Format: Bearer ${token}.

  Example of JWT signing in Go:

  ```go
  import (
   "fmt"
   "time"

   "github.com/golang-jwt/jwt/v5"
  )

  // Claims Required parameters for authentication requests
  type Claims struct {
    JWTPayload // Custom JWT payload structure
    jwt.RegisteredClaims
  }

  // Generate Signature encoding
  func Generate(payload JWTPayload, name, secretKey string) (string, error) {
    claims := Claims{
      payload,
      jwt.RegisteredClaims{
        Issuer:   name, // Platform Token name
        IssuedAt: jwt.NewNumericDate(time.Now().UTC()), // Current UTC time
      },
    }
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString([]byte(secretKey))
  }
  ```

  Example of JWT signing in Python:

  ```python
  from datetime import datetime, timezone
  import jwt

  class JWTPayload:
    """Custom JWT payload structure"""
    pass

  def generate(payload: JWTPayload, name: str, secret_key: str) -> str:
  claims = {
      "iss": name,  # Issuer - Platform Token name
      "iat": datetime.now(timezone.utc),  # IssuedAt - Current UTC time

  # You can add custom payload fields here
  # If payload has attributes, you can access them via vars(payload) or payload.__dict__
  }

  token = jwt.encode(claims, secret_key, algorithm="HS256")
  return token
  ```

  Example of JWT signing in Node.js:

  ```javascript
  // Dependency: npm install jsonwebtoken
  const jwt = require('jsonwebtoken')

  /**
   * Generate a signed JWT.
   * @param {object} payload Custom JWT payload fields
   * @param {string} name Platform Token name
   * @param {string} secretKey Platform Token secret_key
   * @returns {string} Signed JWT
   */
  function generate(payload, name, secretKey) {
    const claims = {
      ...payload,
      iss: name, // Issuer - Platform Token name
      iat: Math.floor(Date.now() / 1000), // IssuedAt - Current UNIX timestamp (seconds)
    }
    return jwt.sign(claims, secretKey, { algorithm: 'HS256' })
  }
  ```

  For more details on JWT, refer to the official documentation.

  Note: Assign the **issueAt** field of **JWT Claims** to the current UNIX timestamp,
  recording the time of the API request.
  **Note: If this time differs from the server time by more than 2 minutes,**
  **the interface will return a signature expiration error.**

## API Response

After a successful token exchange request, a **24-hour** valid temporary token will be returned,
which can be used to call OpenAPI interfaces.

For details on OpenAPI interfaces, refer to the [Cloud Native Build OpenAPI Documentation](https://api.cnbprod.alpha.qq.com).

## Request Example

curl request example:

```bash
curl -X POST 3rd.cnbprod.alpha.qq.com/platform-token/-/user/someone \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoiIiwic2NvcGUiO"
```

Response example:

```json
{ "token": "bHaDbC6esm88116aZOGDbpH26fL" }
```
