身份服务 API

本页面的翻译未经核对,可能存在翻译质量不佳、错翻、漏翻等情况。您可以在 Forgejo 存储库 打开 Issue、提交 Pull Request 或邮件联系我们提出改进建议和参与翻译与核对。

Matrix 的客户端-服务器与服务器-服务器 API 主要使用 Matrix 用户标识符。在某些情况下,我们需要以其他(“第三方”)标识符,或“3PID”(如电子邮件地址或电话号码)来引用用户。本身份服务规范描述了如何建立、验证和使用第三方标识符与 Matrix 用户标识符之间的映射。理论上,本规范可适用于任意 3PID,但实际上目前仅针对电子邮件地址和电话号码进行了具体实现。

基本原则

身份服务器的目的是验证、存储并响应有关用户身份的问题。具体来说,它存储如下关联:“标识符 X 与标识符 Y 代表同一用户”,其中这些身份可存在于不同系统(如电子邮件地址、电话号码、Matrix 用户 ID 等)中。

身份服务器拥有若干私钥-公钥对。当被查询某项关联时,它会使用其私钥对该关联的详细信息进行签名。客户端可通过验证身份服务器公钥的签名,来校验关于关联的声明。

通常情况下,身份服务器被视为可靠的权威。它们并不总能提供已验证关联的证据,但会声称已完成验证。具体信任哪台身份服务器,由客户端自行决定。

3PID 类型详见3PID 类型附录。

API 标准

Matrix 身份服务器通信的强制基线是通过 HTTP API 交换 JSON 对象。通信必须使用 HTTPS。

所有 POSTPUT 端点(出于历史原因,POST /_matrix/identity/v2/account/logout 除外)都要求客户端在请求体中提交一个(可能为空的)JSON 对象。对于带有 JSON 请求体的请求,客户端应提供 Content-Type: application/json 头,但这非强制要求。

同样,所有端点都需返回 JSON 对象。服务器返回 JSON 时,必须包括 Content-Type: application/json 响应头。

所有请求或响应中的 JSON 数据,必须采用 UTF-8 编码。

标准错误响应

若在 Matrix API 层发生错误,必须返回“标准错误响应”。其格式为如下 JSON 对象:

{
  "errcode": "<error code>",
  "error": "<error message>"
}

error 字符串为人类可读的错误信息,通常描述出错原因。errcode 字符串为唯一字符串,便于处理错误信息,如 M_FORBIDDEN。依据错误类型,可能含有其他键,但 errorerrcode 两个键必须始终存在。

部分标准错误码如下:

M_NOT_FOUND 请求的资源无法找到。

M_MISSING_PARAMS 请求缺少一个或多个参数。

M_INVALID_PARAM 请求包含一个或多个无效参数。

M_SESSION_NOT_VALIDATED Session 尚未验证。

M_NO_VALID_SESSION 根据提供参数找不到相关 Session。

M_SESSION_EXPIRED Session 已过期,需重新创建。

M_INVALID_EMAIL 提供的电子邮件地址无效。

M_EMAIL_SEND_ERROR 发送邮件时出错。通常发生在验证给定邮箱所有权时。

M_INVALID_ADDRESS 提供的第三方地址无效。

M_SEND_ERROR 发送通知时出错。通常见于验证第三方地址所有权时。

M_UNRECOGNIZED 请求中包含未识别的值,如未知的 token 或 medium。

当服务器无法理解请求时,也会使用此响应。若端点未实现,返回 HTTP 状态码 404;若实现了但使用了错误的 HTTP 方法,返回 405。

M_THREEPID_IN_USE 第三方标识符已被他人使用。该错误通常会包含额外的 mxid 字段,以标明该 3PID 的所有者。

M_UNKNOWN 发生未知错误。

隐私

身份信息关系隐私敏感。身份服务器存在的目的是提供身份信息,但访问应受到限制,以避免泄露潜在的敏感数据。尤其应避免构建大规模的身份关联网络。因此,API 通常允许将 3PID 映射到 Matrix 用户身份,但禁止反向映射(即不能查询某 Matrix 用户 ID 关联有哪些 3PID,也不能批量获取一个 3PID 关联的全部身份)。

Web 浏览器客户端

部分客户端可能在 Web 浏览器或类似环境下运行。此时,身份服务器应响应预检(pre-flight)请求,并在所有请求中返回跨域资源共享(CORS)头。

当客户端以 OPTIONS 请求访问服务器时,服务器需返回对应路由的 CORS 头。建议服务器所有请求返回以下 CORS 头:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization

API 版本检查

GET /_matrix/identity/versions


Added in v1.1

Gets the versions of the specification supported by the server.

Values will take the form vX.Y or rX.Y.Z in historical cases. See the Specification Versioning for more information.

All supported versions, including patch versions, are reported by the server.

Rate-limited: No
Requires authentication: No

Request

No request parameters or request body.


Responses

Status Description
200 The versions supported by the server.

200 response

Name Type Description
versions [string]

Required: The supported versions.

{
  "versions": [
    "r0.2.0",
    "r0.2.1",
    "v1.1"
  ]
}

认证

身份服务 API 的大多数端点都要求认证,以确保请求用户已接受所有相关政策,并有权限发起请求。

身份服务器采用类似 Client-Server API 的访问令牌方案进行用户认证。身份服务器发放的访问令牌不能用于认证 Client-Server API 请求。

访问令牌可通过请求头以 Bearer 方式提供:Authorization: Bearer TheTokenHere

客户端也可以(但不推荐)通过查询字符串参数提供访问令牌:access_token=TheTokenHere。为避免令牌泄漏到访问日志或 HTTP 日志,不推荐客户端再采用这种方式。

身份服务器必须同时支持这两种方式。

[Changed in v1.11] 通过查询字符串参数传递访问令牌已被弃用。

若缺少或认证凭据无效,HTTP 响应为 401,错误码为 M_UNAUTHORIZED

GET /_matrix/identity/v2/account


Gets information about what user owns the access token used in the request.

Rate-limited: No
Requires authentication: Yes

Request

No request parameters or request body.


Responses

Status Description
200 The token holder’s information.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

Name Type Description
user_id string

Required: The user ID which registered the token.

{
  "user_id": "@alice:example.org"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

POST /_matrix/identity/v2/account/logout


Logs out the access token, preventing it from being used to authenticate future requests to the server.

Rate-limited: No
Requires authentication: Yes

Request

No request parameters or request body.


Responses

Status Description
200 The token was successfully logged out.
401 The token is not registered or is otherwise unknown to the server.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

{}

401 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_UNKNOWN_TOKEN",
  "error": "Unrecognised access token"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

POST /_matrix/identity/v2/account/register


Exchanges an OpenID token from the homeserver for an access token to access the identity server. The request body is the same as the values returned by /openid/request_token in the Client-Server API.

Rate-limited: No
Requires authentication: No

Request

Request body

OpenIdCredentials
Name Type Description
access_token string

Required: An access token the consumer may use to verify the identity of the person who generated the token. This is given to the federation API GET /openid/userinfo to verify the user’s identity.

expires_in integer

Required: The number of seconds before this token expires and a new one must be generated.

matrix_server_name string

Required: The homeserver domain the consumer should use when attempting to verify the user’s identity.

token_type string

Required: The string Bearer.

Request body example


Responses

Status Description
200 A token which can be used to authenticate future requests to the identity server.

200 response

Name Type Description
token string

Required: An opaque string representing the token to authenticate future requests to the identity server with.

{
  "token": "abc123_OpaqueString"
}

服务条款

身份服务器建议配置服务条款(或类似政策),以确保用户同意服务器处理其数据。为此,身份服务器可以对几乎所有需认证的 API 端点返回 HTTP 403 和错误码 M_TERMS_NOT_SIGNED。该状态表明,用户需接受最新服务条款后才能继续操作。

所有支持认证的端点都可能返回 M_TERMS_NOT_SIGNED 错误。收到此错误后,客户端应调用 GET /terms 获取服务器提供的服务条款,并与用户的 m.accepted_terms 账号数据(下文介绍)进行比较,再向用户展示尚未接受的服务条款,并提供同意的选项。用户选择后(如适用),客户端调用 POST /terms 提交已接受的条款。服务器不可假定客户端会一次性提交所有待同意的条款,客户端也不可假定服务器接收到这些条款后就不会再次响应 M_TERMS_NOT_SIGNED。用户刚同意的条款会追加到 m.accepted_terms

m.accepted_terms


A list of terms URLs the user has previously accepted. Clients SHOULD use this to avoid presenting the user with terms they have already agreed to.

Event type: Message event

Content

Name Type Description
accepted [string]

The list of URLs the user has previously accepted. Should be appended to when the user agrees to new terms.

Examples

{
  "content": {
    "accepted": [
      "https://example.org/somewhere/terms-1.2-en.html",
      "https://example.org/somewhere/privacy-1.2-en.html"
    ]
  },
  "type": "m.accepted_terms"
}

GET /_matrix/identity/v2/terms


Gets all the terms of service offered by the server. The client is expected to filter through the terms to determine which terms need acceptance from the user. Note that this endpoint does not require authentication.

Rate-limited: No
Requires authentication: No

Request

No request parameters or request body.


Responses

Status Description
200 The terms of service offered by the server.

200 response

Name Type Description
policies {string: Policy Object}

Required: The policies the server offers. Mapped from arbitrary ID (unused in this version of the specification) to a Policy Object.

Policy Object
Name Type Description
version string

Required: The version for the policy. There are no requirements on what this might be and could be “alpha”, semantically versioned, or arbitrary.

<Other properties> Internationalised Policy

The policy information for the specified language.

Internationalised Policy
Name Type Description
name string

Required: The translated name of the policy.

url string

Required: The URL, which should include the policy ID, version, and language in it, to be presented to the user as the policy. URLs should have all three criteria to avoid conflicts when the policy is updated in the future: for example, if this was “https://example.org/terms.html" then the server would be unable to update it because the client would have already added that URL to the m.accepted_terms collection.

{
  "policies": {
    "privacy_policy": {
      "en": {
        "name": "Privacy Policy",
        "url": "https://example.org/somewhere/privacy-1.2-en.html"
      },
      "fr": {
        "name": "Politique de confidentialité",
        "url": "https://example.org/somewhere/privacy-1.2-fr.html"
      },
      "version": "1.2"
    },
    "terms_of_service": {
      "en": {
        "name": "Terms of Service",
        "url": "https://example.org/somewhere/terms-2.0-en.html"
      },
      "fr": {
        "name": "Conditions d'utilisation",
        "url": "https://example.org/somewhere/terms-2.0-fr.html"
      },
      "version": "2.0"
    }
  }
}

POST /_matrix/identity/v2/terms


Called by a client to indicate that the user has accepted/agreed to the included set of URLs. Servers MUST NOT assume that the client will be sending all previously accepted URLs and should therefore append the provided URLs to what the server already knows has been accepted.

Clients MUST provide the URL of the policy in the language that was presented to the user. Servers SHOULD consider acceptance of any one language’s URL as acceptance for all other languages of that policy.

The server should avoid returning M_TERMS_NOT_SIGNED because the client may not be accepting all terms at once.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
user_accepts [string]

Required: The URLs the user is accepting in this request.

Request body example

{
  "user_accepts": [
    "https://example.org/somewhere/terms-2.0-en.html"
  ]
}

Responses

Status Description
200 The server has considered the user as having accepted the provided URLs.

200 response

{}

状态检查

GET /_matrix/identity/v2


Checks that an identity server is available at this API endpoint.

To discover that an identity server is available at a specific URL, this endpoint can be queried and will return an empty object.

This is primarily used for auto-discovery and health check purposes by entities acting as a client for the identity server.

Rate-limited: No
Requires authentication: No

Request

No request parameters or request body.


Responses

Status Description
200 An identity server is ready to serve requests.

200 response

{}

密钥管理

身份服务器拥有若干长期公钥-私钥对。命名方式为 算法:标识符,如 ed25519:0。签名关联时,遵循标准的签名 JSON算法。

身份服务器还可以管理一些短期公私钥对,这些密钥的用途和生命周期可与长期密钥不同。

GET /_matrix/identity/v2/pubkey/ephemeral/isvalid


Check whether a short-term public key is valid.

Rate-limited: No
Requires authentication: No

Request

Request parameters

query parameters
Name Type Description
public_key string

Required: The unpadded base64-encoded public key to check.


Responses

Status Description
200 The validity of the public key.

200 response

Name Type Description
valid boolean

Required: Whether the public key is recognised and is currently valid.

{
  "valid": true
}

GET /_matrix/identity/v2/pubkey/isvalid


Check whether a long-term public key is valid. The response should always be the same, provided the key exists.

Rate-limited: No
Requires authentication: No

Request

Request parameters

query parameters
Name Type Description
public_key string

Required: The unpadded base64-encoded public key to check.


Responses

Status Description
200 The validity of the public key.

200 response

Name Type Description
valid boolean

Required: Whether the public key is recognised and is currently valid.

{
  "valid": true
}

GET /_matrix/identity/v2/pubkey/{keyId}


Get the public key for the passed key ID.

Rate-limited: No
Requires authentication: No

Request

Request parameters

path parameters
Name Type Description
keyId string

Required: The ID of the key. This should take the form algorithm:identifier where algorithm identifies the signing algorithm, and the identifier is an opaque string.


Responses

Status Description
200 The public key exists.
404 The public key was not found.

200 response

Name Type Description
public_key string

Required: Unpadded Base64 encoded public key.

{
  "public_key": "VXuGitF39UH5iRfvbIknlvlAVKgD1BsLDMvBf0pmp7c"
}

404 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_NOT_FOUND",
  "error": "The public key was not found"
}

关联查询

GET /_matrix/identity/v2/hash_details


Gets parameters for hashing identifiers from the server. This can include any of the algorithms defined in this specification.

Rate-limited: No
Requires authentication: Yes

Request

No request parameters or request body.


Responses

Status Description
200 The hash function information.

200 response

Name Type Description
algorithms [string]

Required: The algorithms the server supports. Must contain at least sha256.

lookup_pepper string

Required: The pepper the client MUST use in hashing identifiers, and MUST supply to the /lookup endpoint when performing lookups.

Servers SHOULD rotate this string often.

{
  "algorithms": [
    "none",
    "sha256"
  ],
  "lookup_pepper": "matrixrocks"
}

POST /_matrix/identity/v2/lookup


Looks up the set of Matrix User IDs which have bound the 3PIDs given, if bindings are available. Note that the format of the addresses is defined later in this specification.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
addresses [string]

Required: The addresses to look up. The format of the entries here depend on the algorithm used. Note that queries which have been incorrectly hashed or formatted will lead to no matches.

Note that addresses are case sensitive: review the 3PID Types to verify the intended case an identifier should be prior to submission/hashing.

algorithm string

Required: The algorithm the client is using to encode the addresses. This should be one of the available options from /hash_details.

pepper string

Required: The pepper from /hash_details. This is required even when the algorithm does not make use of it.

Request body example

{
  "addresses": [
    "4kenr7N9drpCJ4AfalmlGQVsOn3o2RHjkADUpXJWZUc",
    "nlo35_T5fzSGZzJApqu8lgIudJvmOQtDaHtr-I4rU7I"
  ],
  "algorithm": "sha256",
  "pepper": "matrixrocks"
}

Responses

Status Description
200 The associations for any matched addresses.
400 The client’s request was invalid in some way. One possible problem could be the pepper being invalid after the server has rotated it - this is presented with the M_INVALID_PEPPER error code. Clients SHOULD make a call to /hash_details to get a new pepper in this scenario, being careful to avoid retry loops. M_INVALID_PARAM can also be returned to indicate the client supplied an algorithm that is unknown to the server.

200 response

Name Type Description
mappings {string: string}

Required: Any applicable mappings of addresses to Matrix User IDs. Addresses which do not have associations will not be included, which can make this property be an empty object.

{
  "mappings": {
    "4kenr7N9drpCJ4AfalmlGQVsOn3o2RHjkADUpXJWZUc": "@alice:example.org"
  }
}

400 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_INVALID_PEPPER",
  "error": "Unknown or invalid pepper - has it been rotated?"
}

客户端行为

在执行查询前,客户端应优先请求 /hash_details 端点,确定服务器支持哪些算法(详见下文)。客户端获取该信息后,形成相应的 /lookup 请求以从服务器获取已知绑定关系。

客户端必须至少支持 sha256 算法。

服务器行为

服务器收到 /lookup 请求后,将查询与其已知的绑定比较,必要时对本地存储的标识进行哈希以确定是否与请求完全匹配。

服务器必须至少支持 sha256 算法。

算法

部分算法在规范中有定义;如有其他需求,客户端和服务器可通过 /hash_details 协商格式。

sha256

客户端与服务器必须至少支持此算法,并且它也是推荐用于查询的算法。

采用此算法时,客户端将查询项转换为以空格分隔的字符串,格式为 <address> <medium> <pepper><pepper> 取自 /hash_details<medium> 通常为小写 emailmsisdn<address> 即要查询的 3PID。例如,若客户端要查询 alice@example.org 的绑定关系,格式为 alice@example.org email ThePepperGoesHere

将 medium 与 pepper 附加到 address,可避免每个 3PID 前缀相同,提升哈希函数抗预计算攻击能力。

每条格式化字符串经 SHA-256(参见 RFC 4634)处理后,结果用 URL-Safe Unpadded Base64 编码(与 room version 4 的事件 ID 格式 类似)。

如使用 pepper matrixrocks,示例查询如下:

"alice@example.com email matrixrocks" -> "4kenr7N9drpCJ4AfalmlGQVsOn3o2RHjkADUpXJWZUc"
"bob@example.com email matrixrocks"   -> "LJwSazmv46n0hlMlsb_iYxI0_HXEqy_yj6Jm636cdT8"
"18005552067 msisdn matrixrocks"      -> "nlo35_T5fzSGZzJApqu8lgIudJvmOQtDaHtr-I4rU7I"

哈希后的字符串集作为 /lookup 请求体内的 addresses 数组。注意,使用的 pepper 必须通过 /lookuppepper 参数一并提交。

none

此算法在身份服务器上执行明文查询。若因安全原因不宜传播明文标识,一般不推荐用该算法,但在某些场景(如基于 LDAP 的身份服务器)无法使用哈希,因此允许(或可选地,客户端)采用该算法查询。

sha256 类似,客户端将查询项格式化为 <address> <medium> 的空格分隔字符串,不含 <pepper>。例如,要查询 alice@example.org 的绑定,格式为 alice@example.org email

格式化字符串作为 /lookup 请求体内的 addresses。注意仍需提供 pepper(以保证客户端先正确查询了 /hash_details)。

安全性注意事项

请参考 MSC2134,其中详细阐述了本节规范的安全考量。此处仅简述规范设计的高层原因。

通常,/lookup 端点用于客户端拥有某 3PID,但希望获取对应的 Matrix 用户 ID 的场景。客户端常在邀请新用户入群或遍历通讯录查找未发现的 Matrix 用户时,用到此接口。恶意身份服务器若能收集到这些明文数据,可能滥用之。为保护未关联 Matrix ID 的 3PID 用户隐私,规范尽量提升批量收集 3PID 的难度。

虽然哈希不能百分百防止收集,但能显著增加批量收集标识的成本。手机号码通过哈希也难以完全隐匿,但这仍优于不加密。

另一种替代方案如 bcrypt 等多轮哈希算法,但考虑到需兼顾移动端与低性能设备,仍须保持加密过程较轻量。

客户端应警惕服务器很久不轮换 pepper,或使用弱 pepper,这可能表明服务器试图暴力破解或利用彩虹表反查地址。同样,支持 none 算法的客户端,至少应向用户警示明文发送标识给身份服务器存在的风险。

某些标识(如手机号、电邮域名、已泄露地址)即使经哈希,仍可通过预计算的彩虹表逆推出原文。例如,手机号一般为 12 位左右,比邮箱更易被攻击。

建立关联

创建关联的流程基于 Session 会话。

在 Session 内,用户可证明其拥有某 3PID。一旦验证通过,用户即可将该 3PID 与 Matrix 用户 ID 关联。注意此流程的认证仅为单向,即用户可将任意已验证 3PID 关联到任意 Matrix 用户 ID,例如我可把自有邮箱地址与 @billg:microsoft.com 关联。

Session 有时效性:会话初建或发生验证时被认为已修改。只有在距离上次修改 24 小时内,Session 才可检查或执行验证。逾期后须新建 Session。

会话发起时,客户端请求对应 /requestToken 端点。身份服务器向用户发送验证 token,用户将该 token 提供给客户端,客户端再提交到 /submitToken 端点,整个会话结束。此时,客户端可选择 /bind 该 3PID,也可以留给其他实体进行绑定。

验证 token 格式

验证 token 的格式由身份服务器自行决定,应适合 3PID 类型(如不宜让用户从短信复制一长串带标点的口令)。

身份服务器采用何种格式皆可,但 token 必须不超过 255 个 Unicode 码点。客户端必须保持 token 不变地传递。

电子邮件关联

POST /_matrix/identity/v2/validate/email/requestToken


Create a session for validating an email address.

The identity server will send an email containing a token. If that token is presented to the identity server in the future, it indicates that that user was able to read the email for that email address, and so we validate ownership of the email address.

Note that homeservers offer APIs that proxy this API, adding additional behaviour on top, for example, /register/email/requestToken is designed specifically for use when registering an account and therefore will inform the user if the email address given is already registered on the server.

Note: for backwards compatibility with previous drafts of this specification, the parameters may also be specified as application/x-form-www-urlencoded data. However, this usage is deprecated.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
client_secret string

Required: A unique string generated by the client, and used to identify the validation attempt. It must be a string consisting of the characters [0-9a-zA-Z.=_-]. Its length must not exceed 255 characters and it must not be empty.

email Email Address

Required: The email address to validate.

next_link URI

Optional. When the validation is completed, the identity server will redirect the user to this URL. This option is ignored when submitting 3PID validation information through a POST request.

send_attempt integer

Required: The server will only send an email if the send_attempt is a number greater than the most recent one which it has seen, scoped to that email + client_secret pair. This is to avoid repeatedly sending the same email in the case of request retries between the POSTing user and the identity server. The client should increment this value if they desire a new email (e.g. a reminder) to be sent. If they do not, the server should respond with success but not resend the email.

Request body example

{
  "client_secret": "monkeys_are_GREAT",
  "email": "alice@example.org",
  "next_link": "https://example.org/congratulations.html",
  "send_attempt": 1
}

Responses

Status Description
200 Session created.
400

An error occurred. Some possible errors are:

  • M_INVALID_EMAIL: The email address provided was invalid.
  • M_EMAIL_SEND_ERROR: The validation email could not be sent.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

Name Type Description
sid string

Required: The session ID. Session IDs are opaque strings generated by the identity server. They must consist entirely of the characters [0-9a-zA-Z.=_-]. Their length must not exceed 255 characters and they must not be empty.

{
  "sid": "123abc"
}

400 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_INVALID_EMAIL",
  "error": "The email address is not valid"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

GET /_matrix/identity/v2/validate/email/submitToken


Validate ownership of an email address.

If the three parameters are consistent with a set generated by a requestToken call, ownership of the email address is considered to have been validated. This does not publish any information publicly, or associate the email address with any Matrix user ID. Specifically, calls to /lookup will not show a binding.

Note that, in contrast with the POST version, this endpoint will be used by end-users, and so the response should be human-readable.

Rate-limited: No
Requires authentication: Yes

Request

Request parameters

query parameters
Name Type Description
client_secret string

Required: The client secret that was supplied to the requestToken call.

sid string

Required: The session ID, generated by the requestToken call.

token string

Required: The token generated by the requestToken call and emailed to the user.


Responses

Status Description
200 Email address is validated.
3XX Email address is validated, and the next_link parameter was provided to the requestToken call. The user must be redirected to the URL provided by the next_link parameter.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.
4XX Validation failed.

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

POST /_matrix/identity/v2/validate/email/submitToken


Validate ownership of an email address.

If the three parameters are consistent with a set generated by a requestToken call, ownership of the email address is considered to have been validated. This does not publish any information publicly, or associate the email address with any Matrix user ID. Specifically, calls to /lookup will not show a binding.

The identity server is free to match the token case-insensitively, or carry out other mapping operations such as unicode normalisation. Whether to do so is an implementation detail for the identity server. Clients must always pass on the token without modification.

Note: for backwards compatibility with previous drafts of this specification, the parameters may also be specified as application/x-form-www-urlencoded data. However, this usage is deprecated.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
client_secret string

Required: The client secret that was supplied to the requestToken call.

sid string

Required: The session ID, generated by the requestToken call.

token string

Required: The token generated by the requestToken call and emailed to the user.

Request body example

{
  "client_secret": "monkeys_are_GREAT",
  "sid": "1234",
  "token": "atoken"
}

Responses

Status Description
200 The success of the validation.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

Name Type Description
success boolean

Required: Whether the validation was successful or not.

{
  "success": true
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

手机号关联

POST /_matrix/identity/v2/validate/msisdn/requestToken


Create a session for validating a phone number.

The identity server will send an SMS message containing a token. If that token is presented to the identity server in the future, it indicates that that user was able to read the SMS for that phone number, and so we validate ownership of the phone number.

Note that homeservers offer APIs that proxy this API, adding additional behaviour on top, for example, /register/msisdn/requestToken is designed specifically for use when registering an account and therefore will inform the user if the phone number given is already registered on the server.

Note: for backwards compatibility with previous drafts of this specification, the parameters may also be specified as application/x-form-www-urlencoded data. However, this usage is deprecated.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
client_secret string

Required: A unique string generated by the client, and used to identify the validation attempt. It must be a string consisting of the characters [0-9a-zA-Z.=_-]. Its length must not exceed 255 characters and it must not be empty.

country string

Required: The two-letter uppercase ISO-3166-1 alpha-2 country code that the number in phone_number should be parsed as if it were dialled from.

next_link URI

Optional. When the validation is completed, the identity server will redirect the user to this URL. This option is ignored when submitting 3PID validation information through a POST request.

phone_number string

Required: The phone number to validate.

send_attempt integer

Required: The server will only send an SMS if the send_attempt is a number greater than the most recent one which it has seen, scoped to that country + phone_number + client_secret triple. This is to avoid repeatedly sending the same SMS in the case of request retries between the POSTing user and the identity server. The client should increment this value if they desire a new SMS (e.g. a reminder) to be sent.

Request body example

{
  "client_secret": "monkeys_are_GREAT",
  "country": "GB",
  "next_link": "https://example.org/congratulations.html",
  "phone_number": "07700900001",
  "send_attempt": 1
}

Responses

Status Description
200 Session created.
400

An error occurred. Some possible errors are:

  • M_INVALID_ADDRESS: The phone number provided was invalid.
  • M_SEND_ERROR: The validation SMS could not be sent.
  • M_DESTINATION_REJECTED: The identity server cannot deliver an SMS to the provided country or region.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

Name Type Description
sid string

Required: The session ID. Session IDs are opaque strings generated by the identity server. They must consist entirely of the characters [0-9a-zA-Z.=_-]. Their length must not exceed 255 characters and they must not be empty.

{
  "sid": "123abc"
}

400 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_INVALID_ADDRESS",
  "error": "The phone number is not valid"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

GET /_matrix/identity/v2/validate/msisdn/submitToken


Validate ownership of a phone number.

If the three parameters are consistent with a set generated by a requestToken call, ownership of the phone number address is considered to have been validated. This does not publish any information publicly, or associate the phone number with any Matrix user ID. Specifically, calls to /lookup will not show a binding.

Note that, in contrast with the POST version, this endpoint will be used by end-users, and so the response should be human-readable.

Rate-limited: No
Requires authentication: Yes

Request

Request parameters

query parameters
Name Type Description
client_secret string

Required: The client secret that was supplied to the requestToken call.

sid string

Required: The session ID, generated by the requestToken call.

token string

Required: The token generated by the requestToken call and sent to the user.


Responses

Status Description
200 Phone number is validated.
3XX Phone number address is validated, and the next_link parameter was provided to the requestToken call. The user must be redirected to the URL provided by the next_link parameter.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.
4XX Validation failed.

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

POST /_matrix/identity/v2/validate/msisdn/submitToken


Validate ownership of a phone number.

If the three parameters are consistent with a set generated by a requestToken call, ownership of the phone number is considered to have been validated. This does not publish any information publicly, or associate the phone number address with any Matrix user ID. Specifically, calls to /lookup will not show a binding.

The identity server is free to match the token case-insensitively, or carry out other mapping operations such as unicode normalisation. Whether to do so is an implementation detail for the identity server. Clients must always pass on the token without modification.

Note: for backwards compatibility with previous drafts of this specification, the parameters may also be specified as application/x-form-www-urlencoded data. However, this usage is deprecated.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
client_secret string

Required: The client secret that was supplied to the requestToken call.

sid string

Required: The session ID, generated by the requestToken call.

token string

Required: The token generated by the requestToken call and sent to the user.

Request body example

{
  "client_secret": "monkeys_are_GREAT",
  "sid": "1234",
  "token": "atoken"
}

Responses

Status Description
200 The success of the validation.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

Name Type Description
success boolean

Required: Whether the validation was successful or not.

{
  "success": true
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

通用

POST /_matrix/identity/v2/3pid/bind


Publish an association between a session and a Matrix user ID.

Future calls to /lookup for any of the session's 3pids will return this association.

Note: for backwards compatibility with previous drafts of this specification, the parameters may also be specified as application/x-form-www-urlencoded data. However, this usage is deprecated.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
client_secret string

Required: The client secret passed to the requestToken call.

mxid string

Required: The Matrix user ID to associate with the 3pids.

sid string

Required: The Session ID generated by the requestToken call.

Request body example

{
  "client_secret": "monkeys_are_GREAT",
  "mxid": "@ears:matrix.org",
  "sid": "1234"
}

Responses

Status Description
200 The association was published.
400

The association was not published.

If the session has not been validated, then errcode will be M_SESSION_NOT_VALIDATED. If the session has timed out, then errcode will be M_SESSION_EXPIRED.

403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.
404 The Session ID or client secret were not found

200 response

Name Type Description
address string

Required: The 3pid address of the user being looked up.

medium string

Required: The medium type of the 3pid.

mxid string

Required: The Matrix user ID associated with the 3pid.

not_after integer

Required: A unix timestamp after which the association is not known to be valid.

not_before integer

Required: A unix timestamp before which the association is not known to be valid.

signatures {string: {string: string}}

Required: The signatures of the verifying identity servers which show that the association should be trusted, if you trust the verifying identity services.

ts integer

Required: The unix timestamp at which the association was verified.

{
  "address": "louise@bobs.burgers",
  "medium": "email",
  "mxid": "@ears:matrix.org",
  "not_after": 4582425849161,
  "not_before": 1428825849161,
  "signatures": {
    "matrix.org": {
      "ed25519:0": "ENiU2YORYUJgE6WBMitU0mppbQjidDLanAusj8XS2nVRHPu+0t42OKA/r6zV6i2MzUbNQ3c3MiLScJuSsOiVDQ"
    }
  },
  "ts": 1428825849161
}

400 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_SESSION_NOT_VALIDATED",
  "error": "This validation session has not yet been completed"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

404 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_NO_VALID_SESSION",
  "error": "No valid session was found matching that sid and client secret"
}

GET /_matrix/identity/v2/3pid/getValidated3pid


Determines if a given 3pid has been validated by a user.

Rate-limited: No
Requires authentication: Yes

Request

Request parameters

query parameters
Name Type Description
client_secret string

Required: The client secret passed to the requestToken call.

sid string

Required: The Session ID generated by the requestToken call.


Responses

Status Description
200 Validation information for the session.
400

The session has not been validated.

If the session has not been validated, then errcode will be M_SESSION_NOT_VALIDATED. If the session has timed out, then errcode will be M_SESSION_EXPIRED.

403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.
404 The Session ID or client secret were not found.

200 response

Name Type Description
address string

Required: The address of the 3pid being looked up.

medium string

Required: The medium type of the 3pid.

validated_at integer

Required: Timestamp, in milliseconds, indicating the time that the 3pid was validated.

{
  "address": "louise@bobs.burgers",
  "medium": "email",
  "validated_at": 1457622739026
}

400 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_SESSION_NOT_VALIDATED",
  "error": "This validation session has not yet been completed"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

404 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_NO_VALID_SESSION",
  "error": "No valid session was found matching that sid and client secret"
}

POST /_matrix/identity/v2/3pid/unbind


Remove an association between a session and a Matrix user ID.

Future calls to /lookup for any of the session’s 3pids will not return the removed association.

The identity server should authenticate the request in one of two ways:

  1. The request is signed by the homeserver which controls the user_id.
  2. The request includes the sid and client_secret parameters, as per /3pid/bind, which proves ownership of the 3PID.

If this endpoint returns a JSON Matrix error, that error should be passed through to the client requesting an unbind through a homeserver, if the homeserver is acting on behalf of a client.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
client_secret string

The client secret passed to the requestToken call.

mxid string

Required: The Matrix user ID to remove from the 3pids.

sid string

The Session ID generated by the requestToken call.

threepid 3PID

Required: The 3PID to remove. Must match the 3PID used to generate the session if using sid and client_secret to authenticate this request.

3PID
Name Type Description
address string

Required: The 3PID address to remove.

medium string

Required: A medium from the 3PID Types Appendix, matching the medium of the identifier to unbind.

Request body example

{
  "client_secret": "monkeys_are_GREAT",
  "mxid": "@ears:example.org",
  "sid": "1234",
  "threepid": {
    "address": "monkeys_have_ears@example.org",
    "medium": "email"
  }
}

Responses

Status Description
200 The association was successfully removed.
400 If the response body is not a JSON Matrix error, the identity server does not support unbinds. If a JSON Matrix error is in the response body, the requesting party should respect the error.
403

The credentials supplied to authenticate the request were invalid. This may also be returned if the identity server does not support the chosen authentication method (such as blocking homeservers from unbinding identifiers).

Another common error code is M_TERMS_NOT_SIGNED where the user needs to agree to more terms in order to continue.

404 If the response body is not a JSON Matrix error, the identity server does not support unbinds. If a JSON Matrix error is in the response body, the requesting party should respect the error.
501 If the response body is not a JSON Matrix error, the identity server does not support unbinds. If a JSON Matrix error is in the response body, the requesting party should respect the error.

200 response

{}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_FORBIDDEN",
  "error": "Invalid homeserver signature"
}

邀请存储

身份服务器可存储针对用户 3PID 的待处理邀请,这些邀请将在 3PID 绑定至 Matrix 用户 ID 后检索到,并可通知用户或供后续查询。

稍后,若 3PID 持有者将其绑定到 Matrix 用户 ID,身份服务器会尝试通过 /3pid/onbind 端点向该 Matrix 用户的 homeserver 发送 HTTP POST 请求。请求必须由身份服务器某长期私钥签名。

POST /_matrix/identity/v2/store-invite


Store pending invitations to a user’s 3pid.

In addition to the request parameters specified below, an arbitrary number of other parameters may also be specified. These may be used in the invite message generation described below.

The service will generate a random token and an ephemeral key used for accepting the invite.

The service also generates a display_name for the inviter, which is a redacted version of address which does not leak the full contents of the address.

The service records persistently all of the above information.

It also generates an email containing all of this data, sent to the address parameter, notifying them of the invitation. The email should reference the inviter_name, room_name, room_avatar, and room_type (if present) from the request here.

Also, the generated ephemeral public key will be listed as valid on requests to /_matrix/identity/v2/pubkey/ephemeral/isvalid.

Currently, invites may only be issued for 3pids of the email medium.

Optional fields in the request should be populated to the best of the server’s ability. Identity servers may use these variables when notifying the address of the pending invite for display purposes.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
address string

Required: The email address of the invited user.

medium string

Required: The literal string email.

room_alias string

The Matrix room alias for the room to which the user is invited. This should be retrieved from the m.room.canonical_alias state event.

room_avatar_url string

The Content URI for the room to which the user is invited. This should be retrieved from the m.room.avatar state event.

room_id string

Required: The Matrix room ID to which the user is invited

room_join_rules string

The join_rule for the room to which the user is invited. This should be retrieved from the m.room.join_rules state event.

room_name string

The name of the room to which the user is invited. This should be retrieved from the m.room.name state event.

room_type string

The type from the m.room.create event’s content. If the create event doesn’t have a specified type, this field is not included.

sender string

Required: The Matrix user ID of the inviting user

sender_avatar_url string

The Content URI for the avatar of the user ID initiating the invite.

sender_display_name string

The display name of the user ID initiating the invite.

Request body example

{
  "address": "foo@example.com",
  "medium": "email",
  "room_alias": "#somewhere:example.org",
  "room_avatar_url": "mxc://example.org/s0meM3dia",
  "room_id": "!something:example.org",
  "room_join_rules": "public",
  "room_name": "Bob's Emporium of Messages",
  "room_type": "m.space",
  "sender": "@bob:example.com",
  "sender_avatar_url": "mxc://example.org/an0th3rM3dia",
  "sender_display_name": "Bob Smith"
}

Responses

Status Description
200 The invitation was stored.
400

An error has occurred.

If the 3pid is already bound to a Matrix user ID, the error code will be M_THREEPID_IN_USE. If the medium is unsupported, the error code will be M_UNRECOGNIZED.

403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.

200 response

Name Type Description
display_name string

Required: The generated (redacted) display name.

public_keys [PublicKey]

Required: A list of [server’s long-term public key, generated ephemeral public key].

token string

Required: The generated token. Must be a string consisting of the characters [0-9a-zA-Z.=_-]. Its length must not exceed 255 characters and it must not be empty.

PublicKey
Name Type Description
key_validity_url string

Required: The URI of an endpoint where the validity of this key can be checked by passing it as a public_key query parameter. See key management.

public_key string

Required: The public key, encoded using unpadded Base64.

{
  "display_name": "f...@b...",
  "public_keys": [
    {
      "key_validity_url": "https://example.com/_matrix/identity/v2/pubkey/isvalid",
      "public_key": "serverPublicKeyBase64"
    },
    {
      "key_validity_url": "https://example.com/_matrix/identity/v2/pubkey/ephemeral/isvalid",
      "public_key": "ephemeralPublicKeyBase64"
    }
  ],
  "token": "sometoken"
}

400 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_THREEPID_IN_USE",
  "error": "Binding already known",
  "mxid": "@alice:example.com"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

临时邀请签名

为支持无法自行进行加密的客户端,身份服务器可提供部分加密能力,帮助其接受邀请。虽然这不如客户端自有加密安全,但在某些场景下仍有用。

POST /_matrix/identity/v2/sign-ed25519


Sign invitation details.

The identity server will look up token which was stored in a call to store-invite, and fetch the sender of the invite.

Rate-limited: No
Requires authentication: Yes

Request

Request body

Name Type Description
mxid string

Required: The Matrix user ID of the user accepting the invitation.

private_key string

Required: The private key, encoded as Unpadded base64.

token string

Required: The token from the call to store-invite.

Request body example

{
  "mxid": "@foo:bar.com",
  "private_key": "base64encodedkey",
  "token": "sometoken"
}

Responses

Status Description
200 The signed JSON of the mxid, sender, and token.
403 The user must do something in order to use this endpoint. One example is an M_TERMS_NOT_SIGNED error where the user must agree to more terms.
404 The token was not found.

200 response

Name Type Description
mxid string

Required: The Matrix user ID of the user accepting the invitation.

sender string

Required: The Matrix user ID of the user who sent the invitation.

signatures {string: {string: string}}

Required: The signature of the mxid, sender, and token.

token string

Required: The token for the invitation.

{
  "mxid": "@foo:bar.com",
  "sender": "@baz:bar.com",
  "signatures": {
    "my.id.server": {
      "ed25519:0": "def987"
    }
  },
  "token": "abc123"
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_TERMS_NOT_SIGNED",
  "error": "Please accept our updated terms of service before continuing"
}

404 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_UNRECOGNIZED",
  "error": "Didn't recognize token"
}