Skip to content

Add Mapping Configuration



POST /api/v1/login_mapping/field/add

Overview

Create a system login mapping from identity attributes to target workspace roles.

Prerequisites and Usage Steps

Prepare the actual identity attribute name/value, active workspace, and role UUID first. Read Mapping Switch and Mode to confirm the switch and mode before creating. A rule snapshot is returned on success; then verify by uuid in the list. Only one active system rule is allowed for the same workspace, source field name, and source field value; put multiple roles in the same targetValues array. Saving a rule does not immediately issue a Token to existing users or change existing sessions. Use a real test identity to validate in subsequent relevant logins.

Request Headers

Parameter Type Required Description
X-Df-SVersion string Signature version for the original path and request body; you cannot omit it and continue using the algorithm on this page.
Example: v20240417
How to obtain or fill in: This page's example uses this fixed version, which matches the example signature algorithm.
X-Df-Access-Key string Y Read APIs can use r or w credentials; write APIs require w credentials.
Example: <external-access-key>
How to obtain or fill in: Assigned by the site administrator as an External API AK; workspace OpenAPI Keys cannot be used.
X-Df-Signature string Y Compute HMAC-SHA256 over the uppercased method, nonce, original full path, timestamp, and original UTF-8 request body joined by spaces, then take the hex digest.
Example: <hmac-sha256-hex>
How to obtain or fill in: Calculate using the matching SK according to External API Signature Authentication; see the complete runnable template below.
X-Df-Timestamp string Y Must be within the signature validity window configured for the site; do not reuse the example time.
Example: 1785427200
How to obtain or fill in: When sending, generate the current Unix seconds string with str(int(time.time())).
X-Df-Nonce string Y Temporary nonce; when resending after a failure, also generate a new value and recalculate the signature.
Example: 97d275ee9f774315a7885ba7347acbd9
How to obtain or fill in: Generate uuid.uuid4().hex anew for each request.

Body Request Parameters

Parameter Type Required Description
targetValues[*] string A single valid role UUID string. Custom roles from different workspaces cannot be mixed; owner is rejected.
Example: readOnly
How to obtain or fill in: Get a single role uuid from the target workspace's Workspace Role List.
workspaceUUID string Y UUID of the target active workspace. Although the modification declaration marks it optional, the current implementation has no fallback to the old value, so it must also be explicitly provided in practice.
Allowed null: False
Example: wksp_example001
How to obtain or fill in: Obtain it from content.data[].uuid in the Workspace List, then read roles for that workspace.
sourceField string Y Required top-level attribute name, maximum 40 characters, case-sensitive. It is not an account standard field alias or JSONPath; non-empty is recommended.
Allowed null: False
Maximum length: 40
Example: department
How to obtain or fill in: Obtain it from the actual userinfo attribute definition of the identity provider/LDAP; content.attributes in Account Details after the account's most recent login can help verify the original key.
sourceValue string Y Required string, maximum 256 characters, exact match. An empty string only matches an empty attribute string and does not mean any value. For list attributes, enter a single element value.
Allowed null: False
Maximum length: 256
Example: 研发部
How to obtain or fill in: Use the actual value of the original identity attribute; verify it from the corresponding key in content.attributes of Account Details or the IdP/LDAP attributes.
targetValues array Y Required complete role array; must not contain owner; null is invalid. [] can be saved, but has no valid target role; do not treat it as a safe way to "disable a rule"; final permission handling depends on the login mode. Deduplicate and use a non-empty role list where possible.
Example: ["readOnly"]
How to obtain or fill in: Obtain the available role uuids for that workspace by workspaceUUID from the Workspace Role List.

Additional Parameter Notes

Authentication methods are described in External API Signature Authentication. This module manages site system login mappings (isSystem=1), and is consumed by third-party logins such as OIDC/LDAP that use the shared login mapping path; it is not a workspace custom mapping or a standalone SAML settings API. Saving the configuration does not immediately batch-recalculate permissions for all existing users; processing is performed according to the mode during subsequent relevant logins.

sourceField reads a top-level key from the raw userinfo of the identity service; case and key name must match exactly; JSONPath and nested paths are not supported. Account customAttributes is not the source for this matching; modifying account attributes also does not change the identity service's next userinfo. sourceValue must be exactly equal to the stringified attribute value, not a regex or contains match. When the attribute is a list, match element by element; matching succeeds if any element equals sourceValue. Multiple matching rules in the same workspace merge valid roles. It is recommended that the identity side provide a stable string attribute; numeric values match by their string form, booleans as True/False, null as None, and objects by their internal string form rather than JSON. Constructing rules with object values is not recommended.

When system mapping is enabled and custom mapping is disabled for the target workspace: ValidOnFirstLogin applies system rules only to accounts with no historical direct workspace associations (history includes deleted associations); it is not equivalent to only determining whether an account is newly created this time. GlobalValid replaces direct roles according to the rules on each relevant login; when no match occurs, it can remove direct membership/role relationships. Append only appends matching system roles; when no match occurs, it does not clear the original direct relationships. If custom mapping is enabled for the workspace, replacement/no-match cleanup is performed according to custom rules for that workspace with priority, and the retention semantics of system Append or first-login mode cannot be applied. Disabling the system switch does not also disable workspace custom rules. Existing direct Owner roles are retained during matching processing; new Owner is not granted through this module.

Request Example

import hashlib
import hmac
import json
import time
import uuid
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

# Replace with the target site address and the External API AK/SK assigned by the administrator.
server = "https://external-api.guance.com"
access_key = "<external-access-key>"
secret_key = "<external-secret-key>"
method = 'POST'
path = '/api/v1/login_mapping/field/add'
query = {}
data = {'workspaceUUID': 'wksp_example001', 'sourceField': 'department', 'sourceValue': '研发部', 'targetValues': ['readOnly']}
full_path = path + ("?" + urlencode(query) if query else "")
body = "" if data is None else json.dumps(data, ensure_ascii=False, separators=(",", ":"))
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
string_to_sign = " ".join([method, nonce, full_path, timestamp, body])
signature = hmac.new(secret_key.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
    "X-Df-Access-Key": access_key,
    "X-Df-Timestamp": timestamp,
    "X-Df-Nonce": nonce,
    "X-Df-Signature": signature,
    "X-Df-SVersion": "v20240417",
}
if data is not None:
    headers["Content-Type"] = "application/json"
request = Request(server + full_path, data=None if data is None else body.encode("utf-8"), headers=headers, method=method)
try:
    with urlopen(request, timeout=30) as result:
        payload = json.loads(result.read().decode("utf-8"))
except HTTPError as error:
    print("HTTP", error.code, error.read().decode("utf-8"))  # Handle by errorCode, content, and traceId; do not output AK/SK.
    raise SystemExit(1)
except (URLError, TimeoutError):
    print('请求结果未知,请先核对目标当前状态及是否已经写入,再决定是否重新签名重试;不要自动重复写请求。')
    raise SystemExit(1)
print(json.dumps(payload, ensure_ascii=False, indent=2))

Response

HTTP 200, unified application/json envelope; External does not automatically inject declaration; list pagination is in content.pageInfo.

Field Type Description
content.id integer or null Record sequence number; may be null for a creation snapshot; operations use uuid.
content.uuid string Mapping record UUID, usually with the lgmp_ prefix.
content.status integer Rule status; active is 0. The list filters 3 but may include other historical statuses; actual login consumption and modification/deletion only process 0.
content.creator string Creator identity; External is usually sys.
content.updator string Updater identity; may be empty if not updated.
content.createAt integer Creation Unix seconds.
content.deleteAt integer Deletion Unix seconds; usually -1 if not deleted.
content.updateAt integer Update Unix seconds; usually -1 if not yet modified.
content.sourceField string Top-level attribute name in the raw userinfo to match.
content.sourceValue string String attribute value to match.
content.targetValues string array List of saved target role UUIDs; you cannot directly assert from historical list items that the roles are still valid.
content.targetValues[] string Single target role UUID.
content.workspaceUUID string Target workspace UUID for this rule.
content.isSystem integer or boolean This module is a system mapping, 1 or true; it is not a workspace custom rule.
{
  "code": 200,
  "content": {
    "id": null,
    "uuid": "lgmp_example001",
    "status": 0,
    "creator": "sys",
    "updator": "",
    "createAt": 1785427200,
    "deleteAt": -1,
    "updateAt": -1,
    "sourceField": "department",
    "sourceValue": "研发部",
    "targetValues": [
      "readOnly"
    ],
    "workspaceUUID": "wksp_example001",
    "isSystem": true
  },
  "errorCode": "",
  "message": "",
  "success": true,
  "traceId": "TRACE-EXAMPLE"
}

Error Response

For authentication, rate limiting, and common request errors, see Common Error Definitions.

Confirmed rule and request errors are listed in the table. Ordinary database/cache/audit exceptions ultimately result in 500 ft.InternalServerError; configuration may have been committed before subsequent errors appear, so read the current state before retrying.

HTTP Status errorCode Trigger Condition Message or Response Description Handling
406 ft.ParameterValidationFailed Request fields are missing, or field values violate the declared validation conditions Parameter parsing failed Check the parameter location, field name, type, and value.
400 ft.RequestJsonFormatError The request JSON syntax is invalid Request JSON format error Fix the JSON according to content.reason, line, and column.
400 ft.JsonFormatError The JSON top level is not an object Some JSON file format error Submit a JSON object according to the parameter table.
401 ft.WKSPNotExistOrReleased The target workspaceUUID does not correspond to an active workspace, or this actually required parameter is omitted during modification Workspace does not exist/or has been released Get the active uuid from the workspace list and explicitly include it in the modification request.
400 ft.LoginMappingNotSupportSetOwner targetValues contains owner Mapping to the owner role is not supported Handle it through the formal Owner handover process; this API only maps allowed other roles.
404 ft.LoginMappingFieldAlreadyExists An active system rule with the same sourceField and sourceValue already exists in the same target workspace The workspace already has the same mapping field name and field value Query and modify the existing rule, or use different attributes and values; this error has HTTP status 404, so do not mistake it for the rule not being created and retry indefinitely.
406 ft.InvalidRoleUuidBelongsWSKP targetValues contains a role UUID that is invalid, deleted, or not within the allowed range for the target workspace The currently set TargetValues contains an invalid role UUID Get a valid uuid from the target workspace role list; do not copy a custom role from another workspace.
500 ft.InternalServerError Database, site configuration cache, audit, or unhandled historical data exception Internal error Keep the traceId and read the rule or switch first to confirm the current state; the database and cache/audit are not in the same transaction, so an error does not prove that nothing was saved.

Feedback

Is this page helpful?