Client-Server API

The client-server API allows clients to send messages, control rooms and synchronise conversation history. It is designed to support both lightweight clients which store no state and lazy-load data from the server as required, as well as heavyweight clients which maintain a full local persistent copy of server state.

List of Endpoints
Required

API Standards

These standards only apply to the APIs defined in the Matrix specification. APIs used by this specification but defined in other specifications, like the OAuth 2.0 API, use their own rules.

The mandatory baseline for client-server communication in Matrix is exchanging JSON objects over HTTP APIs. More efficient transports may be specified in future as optional extensions.

HTTPS is recommended for communication. The use of plain HTTP is not recommended outside test environments.

Clients are authenticated using opaque access_token strings (see Client Authentication for details).

All POST and PUT endpoints, with the exception of those listed below, require the client to supply a request body containing a (potentially empty) JSON object. Clients should supply a Content-Type header of application/json for all requests with JSON bodies, but this is not required.

The exceptions are:

Similarly, all endpoints require the server to return a JSON object, with the exception of 200 responses to the media download endpoints in the Content Repository module. Servers must include a Content-Type header of application/json for all JSON responses.

All JSON data, in requests or responses, must be encoded using UTF-8.

See also Conventions for Matrix APIs in the Appendices for conventions which all Matrix APIs are expected to follow, and Web Browser Clients below for additional requirements for server responses.

Standard error response

Any errors which occur at the Matrix API level MUST return a “standard error response”. This is a JSON object which looks like:

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

The error string will be a human-readable error message, usually a sentence explaining what went wrong.

The errcode string will be a unique string which can be used to handle an error message e.g. M_FORBIDDEN. Error codes should have their namespace first in ALL CAPS, followed by a single _. For example, if there was a custom namespace com.mydomain.here, and a FORBIDDEN code, the error code should look like COM.MYDOMAIN.HERE_FORBIDDEN. Error codes defined by this specification should start with M_.

Some errcodes define additional keys which should be present in the error response object, but the keys error and errcode MUST always be present.

Errors are generally best expressed by their error code rather than the HTTP status code returned. When encountering the error code M_UNKNOWN, clients should prefer the HTTP status code as a more reliable reference for what the issue was. For example, if the client receives an error code of M_NOT_FOUND but the request gave a 400 Bad Request status code, the client should treat the error as if the resource was not found. However, if the client were to receive an error code of M_UNKNOWN with a 400 Bad Request, the client should assume that the request being made was invalid.

Common error codes

These error codes can be returned by any API endpoint:

M_BAD_JSON
Request contained valid JSON, but it was malformed in some way, e.g. missing required keys, invalid values for keys.
M_FORBIDDEN
Forbidden access, e.g. joining a room without permission, failed login.
M_LIMIT_EXCEEDED
Too many requests have been sent in a short period of time. Wait a while then try again. See Rate limiting.
M_MISSING_TOKEN
No access token was specified for the request.
M_NOT_FOUND
No resource was found for this request.
M_NOT_JSON
Request did not contain valid JSON.
M_RESOURCE_LIMIT_EXCEEDED
The request cannot be completed because the homeserver has reached a resource limit imposed on it. For example, a homeserver held in a shared hosting environment may reach a resource limit if it starts using too much memory or disk space. The error MUST have an admin_contact field to provide the user receiving the error a place to reach out to. Typically, this error will appear on routes which attempt to modify state (e.g.: sending messages, account data, etc) and not routes which only read state (e.g.: /sync, /user/{userId}/account_data/{type}, etc).
M_UNKNOWN
An unknown error has occurred.
M_UNKNOWN_DEVICE
[Added in v1.17] The device ID supplied by the application service does not belong to the user ID during identity assertion.
M_UNKNOWN_TOKEN
The access or refresh token specified was not recognised.

An additional response parameter, soft_logout, might be present on the response for 401 HTTP status codes. See the soft logout section for more information.

M_UNRECOGNIZED
The server did not understand the request. This is expected to be returned with a 404 HTTP status code if the endpoint is not implemented or a 405 HTTP status code if the endpoint is implemented, but the incorrect HTTP method is used.
M_USER_LIMIT_EXCEEDED
[Added in v1.18] The request cannot be completed because the user has exceeded (or the request would cause them to exceed) a limit associated with their account. For example, a user may have reached their allocated storage quota, reached a maximum number of allowed rooms, devices, or other account-scoped resources, or exceeded usage limits for specific features.

The error response MUST have an info_uri field (string), which is a URI that the client can present to the user to provide more context on the encountered limit and, if applicable, guidance on how to increase the limit. The homeserver MAY return different values for info_uri depending on the type of limit reached.

The error response MAY include a can_upgrade field (boolean, default false). If true, it indicates that the specific limit encountered can be increased, for example by upgrading the user’s account tier. If absent or false, the limit is a hard limit that cannot be increased.

The HTTP status code will depend on depend on the particular endpoint.

Example response:

{
  "errcode": "M_USER_LIMIT_EXCEEDED",
  "error": "You have exceeded your storage quota of 10GB",
  "info_uri": "https://example.com/homeserver/about?limit_type=quota",
  "can_upgrade": true
}
M_USER_LOCKED
The account has been locked and cannot be used at this time.
M_USER_SUSPENDED
The account has been suspended and can only be used for limited actions at this time.

Other error codes

The following error codes are specific to certain endpoints.

M_BAD_STATE
The state change requested cannot be performed, such as attempting to unban a user who is not banned.
M_CANNOT_LEAVE_SERVER_NOTICE_ROOM
The user is unable to reject an invite to join the server notices room. See the Server Notices module for more information.
M_CAPTCHA_INVALID
The Captcha provided did not match what was expected.
M_CAPTCHA_NEEDED
A Captcha is required to complete the request.
M_EXCLUSIVE
The resource being requested is reserved by an application service, or the application service making the request has not created the resource.
M_GUEST_ACCESS_FORBIDDEN
The room or resource does not permit guests to access it.
M_INCOMPATIBLE_ROOM_VERSION
The client attempted to join a room that has a version the server does not support. Inspect the room_version property of the error response for the room’s version.
M_INVALID_PARAM
A parameter that was specified has the wrong value. For example, the server expected an integer and instead received a string.
M_INVALID_ROOM_STATE
Sent when the initial state given to the createRoom API is invalid.
M_INVALID_USERNAME
Encountered when trying to register a user ID which is not valid.
M_MISSING_PARAM
A required parameter was missing from the request.
M_ROOM_IN_USE
Sent when the room alias given to the createRoom API is already in use.
M_SERVER_NOT_TRUSTED
The client’s request used a third-party server, e.g. identity server, that this server does not trust.
M_THREEPID_AUTH_FAILED
Authentication could not be performed on the third-party identifier.
M_THREEPID_DENIED
The server does not permit this third-party identifier. This may happen if the server only permits, for example, email addresses from a particular domain.
M_THREEPID_IN_USE
The third party identifier specified by the client is not acceptable because it is already in use in some way.
M_THREEPID_MEDIUM_NOT_SUPPORTED
The homeserver does not support adding a third party identifier of the given medium.
M_THREEPID_NOT_FOUND
Sent when a threepid given to an API cannot be used because no record matching the threepid was found.
M_TOO_LARGE
The request or entity was too large.
M_UNAUTHORIZED
The request was not correctly authorised. Usually due to login failures.
M_UNSUPPORTED_ROOM_VERSION
The client’s request to create a room used a room version that the server does not support.
M_USER_DEACTIVATED
The user ID associated with the request has been deactivated. Typically for endpoints that prove authentication, such as /login.
M_USER_IN_USE
Encountered when trying to register a user ID which has been taken.

Rate limiting

Homeservers SHOULD implement rate limiting to reduce the risk of being overloaded. If a request is refused due to rate limiting, it should return a standard error response of the form:

{
  "errcode": "M_LIMIT_EXCEEDED",
  "error": "string",
  "retry_after_ms": integer (optional, deprecated)
}

Homeservers SHOULD include a Retry-After header for any response with a 429 status code.

The retry_after_ms property MAY be included to tell the client how long they have to wait in milliseconds before they can try again. This property is deprecated, in favour of the Retry-After header.

[Changed in v1.10]: retry_after_ms property deprecated in favour of Retry-After header.

Transaction identifiers

The client-server API typically uses HTTP PUT to submit requests with a client-generated transaction identifier in the HTTP path.

The purpose of the transaction ID is to allow the homeserver to distinguish a new request from a retransmission of a previous request so that it can make the request idempotent.

The transaction ID should only be used for this purpose.

After the request has finished, clients should change the {txnId} value for the next request. How this is achieved, is left as an implementation detail. It is recommended that clients use either version 4 UUIDs or a concatenation of the current timestamp and a monotonically increasing integer.

The homeserver should identify a request as a retransmission if the transaction ID is the same as a previous request, and the path of the HTTP request is the same.

Where a retransmission has been identified, the homeserver should return the same HTTP response code and content as the original request. For example, PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId} would return a 200 OK with the event_id of the original request in the response body.

The scope of a transaction ID is for a single device, and a single HTTP endpoint. In other words: a single device could use the same transaction ID for a request to PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId} and PUT /_matrix/client/v3/sendToDevice/{eventType}/{txnId}, and the two requests would be considered distinct because the two are considered separate endpoints. Similarly, if a client logs out and back in between two requests using the same transaction ID, the requests are distinct because the act of logging in and out creates a new device (unless an existing device_id is given during the login process). On the other hand, if a client re-uses a transaction ID for the same endpoint after refreshing an access token, it will be assumed to be a duplicate request and ignored. See also Relationship between access tokens and devices.

Some API endpoints may allow or require the use of POST requests without a transaction ID. Where this is optional, the use of a PUT request is strongly recommended.

Prior to v1.7, transaction IDs were scoped to “client sessions” rather than devices.

Web Browser Clients

It is realistic to expect that some clients will be written to be run within a web browser or similar environment. In these cases, the homeserver should respond to pre-flight requests and supply Cross-Origin Resource Sharing (CORS) headers on all requests.

Servers MUST expect that clients will approach them with OPTIONS requests, allowing clients to discover the CORS headers. All endpoints in this specification support the OPTIONS method, however the server MUST NOT perform any logic defined for the endpoints when approached with an OPTIONS request.

When a client approaches the server with a request, the server should respond with the CORS headers for that route. The recommended CORS headers to be returned by servers on all requests are:

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

[Added in v1.13] The recommended value of the Access-Control-Allow-Methods header only covers the existing endpoints in the specification. Servers which support additional endpoints or methods should add those methods as well.

This section will be updated whenever a new method is supported by an endpoint. Examples of possible future-use methods include PATCH and HEAD.

Server Discovery

In order to allow users to connect to a Matrix server without needing to explicitly specify the homeserver’s URL or other parameters, clients SHOULD use an auto-discovery mechanism to determine the server’s URL based on a user’s Matrix ID. Auto-discovery should only be done at login time.

In this section, the following terms are used with specific meanings:

PROMPT Retrieve the specific piece of information from the user in a way which fits within the existing client user experience, if the client is inclined to do so. Failure can take place instead if no good user experience for this is possible at this point.

IGNORE Stop the current auto-discovery mechanism. If no more auto-discovery mechanisms are available, then the client may use other methods of determining the required parameters, such as prompting the user, or using default values.

FAIL_PROMPT Inform the user that auto-discovery failed due to invalid/empty data and PROMPT for the parameter.

FAIL_ERROR Inform the user that auto-discovery did not return any usable URLs. Do not continue further with the current login process. At this point, valid data was obtained, but no server is available to serve the client. No further guess should be attempted and the user should make a conscientious decision what to do next.

Well-known URIs

Matrix facilitates automatic discovery for the Client-Server API base URL and more via the RFC 8615 “Well-Known URI” method. This method uses JSON files at a predetermined location on the root path /.well-known/ to specify parameter values.

Diverging from the rest of the endpoints in the Client-Server spec, these files can not be provided on the base URL that the Client-Server API is reachable on, as it is yet to be discovered. Instead, they can be reached via HTTPS on the server name’s hostname as domain.

Servers hosting the .well-known JSON file SHOULD offer CORS headers, as per the CORS section in this specification.

The flow for auto-discovery is as follows:

  1. Extract the server name from the user’s Matrix ID by splitting the Matrix ID at the first colon.
  2. Extract the hostname from the server name as described by the grammar.
  3. Make a GET request to https://hostname/.well-known/matrix/client.
    1. If the returned status code is 404, then IGNORE.
    2. If the returned status code is not 200, or the response body is empty, then FAIL_PROMPT.
    3. Parse the response body as a JSON object
      1. If the content cannot be parsed, then FAIL_PROMPT.
    4. Extract the base_url value from the m.homeserver property. This value is to be used as the base URL of the homeserver.
      1. If this value is not provided, then FAIL_PROMPT.
    5. Validate the homeserver base URL:
      1. Parse it as a URL. If it is not a URL, then FAIL_ERROR.
      2. Clients SHOULD validate that the URL points to a valid homeserver before accepting it by connecting to the /_matrix/client/versions endpoint, ensuring that it does not return an error, and parsing and validating that the data conforms with the expected response format. If any step in the validation fails, then FAIL_ERROR. Validation is done as a simple check against configuration errors, in order to ensure that the discovered address points to a valid homeserver.
      3. It is important to note that the base_url value might include a trailing /. Consumers should be prepared to handle both cases.
    6. If the m.identity_server property is present, extract the base_url value for use as the base URL of the identity server. Validation for this URL is done as in the step above, but using /_matrix/identity/v2 as the endpoint to connect to. If the m.identity_server property is present, but does not have a base_url value, then FAIL_PROMPT.

GET /.well-known/matrix/client


Gets discovery information about the domain. The file may include additional keys, which MUST follow the Java package naming convention, e.g. com.example.myapp.property. This ensures property names are suitably namespaced for each application and reduces the risk of clashes.

This endpoint should be accessed with the hostname of the homeserver’s server name by making a GET request to https://hostname/.well-known/matrix/client.

Note that this endpoint is not necessarily handled by the homeserver, but by another webserver, to be used for discovering the homeserver URL.

Rate-limited: No
Requires authentication: No

Request

No request parameters or request body.


Responses

Status Description
200 Server discovery information.
404 No server discovery information available.

200 response

Discovery Information
Name Type Description
m.homeserver Homeserver Information

Required: Used by clients to discover homeserver information.

m.identity_server Identity Server Information

Used by clients to discover identity server information.

<Other properties>

Application-dependent keys using Java package naming convention.

Homeserver Information
Name Type Description
base_url URI

Required: The base URL for the homeserver for client-server connections.

Identity Server Information
Name Type Description
base_url URI

Required: The base URL for the identity server for client-server connections.

{
  "m.homeserver": {
    "base_url": "https://matrix.example.com"
  },
  "m.identity_server": {
    "base_url": "https://identity.example.com"
  },
  "org.example.custom.property": {
    "app_url": "https://custom.app.example.org"
  }
}

GET /.well-known/matrix/support


Added in v1.10

Gets server admin contact and support page of the domain.

Like the well-known discovery URI, this endpoint should be accessed with the hostname of the homeserver’s server name by making a GET request to https://hostname/.well-known/matrix/support.

Note that this endpoint is not necessarily handled by the homeserver. It may be served by another webserver, used for discovering support information for the homeserver.

Rate-limited: No
Requires authentication: No

Request

No request parameters or request body.


Responses

Status Description
200 Server support information.
404 No server support information available.

200 response

Name Type Description
contacts [Contact]

Ways to contact the server administrator.

At least one of contacts or support_page is required. If only contacts is set, it must contain at least one item.

support_page URI

The URL of a page to give users help specific to the homeserver, like extra login/registration steps.

At least one of contacts or support_page is required.

Contact
Name Type Description
email_address Email Address

An email address to reach the administrator.

At least one of matrix_id or email_address is required.

matrix_id User ID

A Matrix User ID representing the administrator.

It could be an account registered on a different homeserver so the administrator can be contacted when the homeserver is down.

At least one of matrix_id or email_address is required.

role string

Required: An informal description of what the contact methods are used for.

m.role.admin is a catch-all role for any queries and m.role.security is intended for sensitive requests.

Unspecified roles are permitted through the use of Namespaced Identifiers.

One of: [m.role.admin, m.role.security].

{
  "contacts": [
    {
      "email_address": "[email protected]",
      "matrix_id": "@admin:example.org",
      "role": "m.role.admin"
    },
    {
      "email_address": "[email protected]",
      "role": "m.role.security"
    }
  ],
  "support_page": "https://example.org/support.html"
}

GET /.well-known/matrix/policy_server


Added in v1.18

Gets public key information for a Policy Server.

Like the well-known discovery URI, this endpoint should be accessed with the hostname of the Policy Server’s server name by making a GET request to https://hostname/.well-known/matrix/policy_server.

Note that this endpoint is not necessarily handled by the homeserver or Policy Server. It may be served by another webserver.

Rate-limited: No
Requires authentication: No

Request

No request parameters or request body.


Responses

Status Description
200 Public keys for the Policy Server. Can be supplied to the m.room.policy state event.
404 No policy server information available.

200 response

Name Type Description
public_keys object

Required: The unpadded base64-encoded public keys for the Policy Server. MUST contain at least ed25519.

Name Type Description
ed25519 string

Required: The unpadded base64-encoded ed25519 public key for the Policy Server.

<Other properties> string

The unpadded base64-encoded public key for the key algorithm.

{
  "public_keys": {
    "ed25519": "6yhHGKhCiXTSEN2ksjV7kX_N6rBQZ3Xb-M7LlC6NS-s"
  }
}

API Versions

Upon connecting, the Matrix client and server need to negotiate which version of the specification they commonly support, as the API evolves over time. The server advertises its supported versions and optionally unstable features to the client, which can then go on to make requests to the endpoints it supports.

GET /_matrix/client/versions


Changed in v1.10: This endpoint can behave differently when authentication is provided.

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.

The server may additionally advertise experimental features it supports through unstable_features. These features should be namespaced and may optionally include version information within their name if desired. Features listed here are not for optionally toggling parts of the Matrix specification and should only be used to advertise support for a feature which has not yet landed in the spec. For example, a feature currently undergoing the proposal process may appear here and eventually be taken off this list once the feature lands in the spec and the server deems it reasonable to do so. Servers can choose to enable some features only for some users, so clients should include authentication in the request to get all the features available for the logged-in user. If no authentication is provided, the server should only return the features available to all users. Servers may wish to keep advertising features here after they’ve been released into the spec to give clients a chance to upgrade appropriately. Additionally, clients should avoid using unstable features in their stable releases.

Rate-limited: No
Requires authentication: Optional

Request

No request parameters or request body.


Responses

Status Description
200 The versions supported by the server.

200 response

Name Type Description
unstable_features {string: boolean}

Experimental features the server supports. Features not listed here, or the lack of this property all together, indicate that a feature is not supported.

versions [string]

Required: The supported versions.

{
  "unstable_features": {
    "org.example.my_feature": true
  },
  "versions": [
    "r0.0.1",
    "v1.1"
  ]
}

Client Authentication

[Changed in v1.15] OAuth 2.0 API added to the specification.

Most API endpoints require the user to identify themselves by presenting previously obtained credentials in the form of an access token. An access token is typically obtained via the Login or Registration processes. Access tokens can expire; a new access token can be generated by using a refresh token.

This specification does not mandate a particular format for the access token. Clients should treat it as an opaque byte sequence. Servers are free to choose an appropriate format. Server implementors may like to investigate macaroons.

Since Matrix 1.15, the Client-Server specification supports two authentication APIs:

The legacy API has existed since the first version of the Matrix specification, while the OAuth 2.0 API has been introduced to rely on a industry standard and its experience rather than implementing a custom protocol that might not follow the best practices.

A homeserver may support one of those two APIs, or both. The two APIs are mutually incompatible, which means that after logging in, clients MUST only use the API that was used to obtain their current access token.

Currently the OAuth 2.0 API doesn’t cover all the use cases of the legacy API, such as automated applications that cannot use a web browser.

[Added in v1.18] A compatibility feature, called OAuth 2.0 aware clients, is available to ease the transition to the OAuth 2.0 API for clients that only support the legacy API.

Authentication API discovery

To discover if a homeserver supports the legacy API, the GET /login endpoint can be used.

To discover if a homeserver supports the OAuth 2.0 API, the GET /auth_metadata endpoint can be used.

In both cases, the server SHOULD respond with 404 and an M_UNRECOGNIZED error code if the corresponding API is not supported.

Account registration

With the legacy API, a client can register a new account with the /register endpoint.

With the OAuth 2.0 API, a client can’t register a new account directly. The end user must do that directly in the homeserver’s web UI. However, the client can signal to the homeserver that the user wishes to create a new account with the prompt=create parameter during authorisation.

[Added in v1.17] Application services can use the /register endpoint to create users regardless of the authentication API supported by the homeserver.

Login

With the legacy API, a client can obtain an access token by using one of the login methods supported by the homeserver at the POST /login endpoint. To invalidate the access token the client must call the /logout endpoint.

With the OAuth 2.0 API, a client can obtain an access token by using one of the grant types supported by the homeserver and authorising the proper scope, as demonstrated in the login flows. To invalidate the access token the client must use token revocation.

Using access tokens

Access tokens may be provided via a request header, using the Authentication Bearer scheme: Authorization: Bearer TheTokenHere.

Clients may alternatively provide the access token via a query string parameter: access_token=TheTokenHere. This method is deprecated to prevent the access token being leaked in access/HTTP logs and SHOULD NOT be used by clients.

Homeservers MUST support both methods.

[Changed in v1.11] Sending the access token as a query string parameter is now deprecated.

When credentials are required but missing or invalid, the HTTP call will return with a status of 401 and the error code, M_MISSING_TOKEN or M_UNKNOWN_TOKEN respectively. Note that an error code of M_UNKNOWN_TOKEN could mean one of four things:

  1. the access token was never valid.
  2. the access token has been logged out.
  3. the access token has been soft logged out.
  4. [Added in v1.3] the access token needs to be refreshed.

When a client receives an error code of M_UNKNOWN_TOKEN, it should:

  • attempt to refresh the token, if it has a refresh token;
  • if soft_logout is set to true, it can offer to re-log in the user, retaining any of the client’s persisted information;
  • otherwise, consider the user as having been logged out.

Relationship between access tokens and devices

Client devices are closely related to access tokens and refresh tokens. Matrix servers should record which device each access token and refresh token are assigned to, so that subsequent requests can be handled correctly. When a refresh token is used to generate a new access token and refresh token, the new access and refresh tokens are now bound to the device associated with the initial refresh token.

During login or registration, the generated access token should be associated with a device_id. The legacy Login and Registration processes auto-generate a new device_id, but a client is also free to provide its own device_id. With the OAuth 2.0 API, the device_id is always provided by the client. The client can generate a new device_id or, provided the user remains the same, reuse an existing device. If the client sets the device_id, the server will invalidate any access and refresh tokens previously assigned to that device.

Refreshing access tokens

[Added in v1.3]

Access tokens can expire after a certain amount of time. Any HTTP calls that use an expired access token will return with an error code M_UNKNOWN_TOKEN, preferably with soft_logout: true. When a client receives this error and it has a refresh token, it should attempt to refresh the access token. Clients can also refresh their access token at any time, even if it has not yet expired. If the token refresh succeeds, the client should use the new token for future requests, and can re-try previously-failed requests with the new token. When an access token is refreshed, a new refresh token may be returned; if a new refresh token is given, the old refresh token will be invalidated, and the new refresh token should be used when the access token needs to be refreshed.

The old refresh token remains valid until the new access token or refresh token is used, at which point the old refresh token is revoked. This ensures that if a client fails to receive or persist the new tokens, it will be able to repeat the refresh operation.

If the token refresh fails and the error response included a soft_logout: true property, then the client can treat it as a soft logout and attempt to obtain a new access token by re-logging in. If the error response does not include a soft_logout: true property, the client should consider the user as being logged out.

With the legacy API, refreshing access tokens is done by calling /refresh. Handling of clients that do not support refresh tokens is up to the homeserver; clients indicate their support for refresh tokens by including a refresh_token: true property in the request body of the /login and /register endpoints. For example, homeservers may allow the use of non-expiring access tokens, or may expire access tokens anyways and rely on soft logout behaviour on clients that don’t support refreshing.

With the OAuth 2.0 API, refreshing access tokens is done with the refresh token grant type, as demonstrated in the token refresh flow. Support for refreshing access tokens is mandatory with this API.

Soft logout

A client can be in a “soft logout” state if the server requires re-authentication before continuing, but does not want to invalidate the client’s session. The server indicates that the client is in a soft logout state by including a soft_logout: true parameter in an M_UNKNOWN_TOKEN error response; the soft_logout parameter defaults to false. If the soft_logout parameter is omitted or is false, this means the server has destroyed the session and the client should not reuse it. That is, any persisted state held by the client, such as encryption keys and device information, must not be reused and must be discarded. If soft_logout is true the client can reuse any persisted state.

[Changed in v1.3] A client that receives such a response can try to refresh its access token, if it has a refresh token available. If it does not have a refresh token available, or refreshing fails with soft_logout: true, the client can acquire a new access token by specifying the device ID it is already using to the login API.

[Changed in v1.12] A client that receives such a response together with an M_USER_LOCKED error code, cannot obtain a new access token until the account has been unlocked.

Account management

With the legacy API, a client can use several endpoints to allow the user to manage their account like changing their password, managing their devices or deactivating their account.

With the OAuth 2.0 API, all account management is done via the homeserver’s web UI that can be accessed by users via the account management URL.

Legacy API

This is the original authentication API that was introduced in the first version of the Client-Server specification and uses custom APIs. Contrary to the OAuth 2.0 API, account management is primarily done in the client’s interface and as such it does not usually require the end user to be redirected to a web UI in their browser.

User-Interactive Authentication API

Overview

Some API endpoints require authentication that interacts with the user. The homeserver may provide many different ways of authenticating, such as user/password auth, login via a single-sign-on server (SSO), etc. This specification does not define how homeservers should authorise their users but instead defines the standard interface which implementations should follow so that ANY client can log in to ANY homeserver.

The process takes the form of one or more ‘stages’. At each stage the client submits a set of data for a given authentication type and awaits a response from the server, which will either be a final success or a request to perform an additional stage. This exchange continues until the final success.

For each endpoint, a server offers one or more ‘flows’ that the client can use to authenticate itself. Each flow comprises a series of stages, as described above. The client is free to choose which flow it follows, however the flow’s stages must be completed in order. Failing to follow the flows in order must result in an HTTP 401 response, as defined below. When all stages in a flow are complete, authentication is complete and the API call succeeds.

User-interactive API in the REST API

In the REST API described in this specification, authentication works by the client and server exchanging JSON dictionaries. The server indicates what authentication data it requires via the body of an HTTP 401 response, and the client submits that authentication data via the auth request parameter.

A client should first make a request with no auth parameter. The homeserver returns an HTTP 401 response, with a JSON body, as follows:

HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
  "flows": [
    {
      "stages": [ "example.type.foo", "example.type.bar" ]
    },
    {
      "stages": [ "example.type.foo", "example.type.baz" ]
    }
  ],
  "params": {
      "example.type.baz": {
          "example_key": "foobar"
      }
  },
  "session": "xxxxxx"
}

In addition to the flows, this object contains some extra information:

  • params: This section contains any information that the client will need to know in order to use a given type of authentication. For each authentication type presented, that type may be present as a key in this dictionary. For example, the public part of an OAuth client ID could be given here.

  • session: This is a session identifier that the client must pass back to the homeserver, if one is provided, in subsequent attempts to authenticate in the same API call.

The client then chooses a flow and attempts to complete the first stage. It does this by resubmitting the same request with the addition of an auth key in the object that it submits. This dictionary contains a type key whose value is the name of the authentication type that the client is attempting to complete. It must also contain a session key with the value of the session key given by the homeserver, if one was given. It also contains other keys dependent on the auth type being attempted. For example, if the client is attempting to complete auth type example.type.foo, it might submit something like this:

POST /_matrix/client/v3/endpoint HTTP/1.1
Content-Type: application/json
{
  "a_request_parameter": "something",
  "another_request_parameter": "something else",
  "auth": {
      "type": "example.type.foo",
      "session": "xxxxxx",
      "example_credential": "verypoorsharedsecret"
  }
}

If the homeserver deems the authentication attempt to be successful but still requires more stages to be completed, it returns HTTP status 401 along with the same object as when no authentication was attempted, with the addition of the completed key which is an array of auth types the client has completed successfully:

HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
  "completed": [ "example.type.foo" ],
  "flows": [
    {
      "stages": [ "example.type.foo", "example.type.bar" ]
    },
    {
      "stages": [ "example.type.foo", "example.type.baz" ]
    }
  ],
  "params": {
      "example.type.baz": {
          "example_key": "foobar"
      }
  },
  "session": "xxxxxx"
}

Individual stages may require more than one request to complete, in which case the response will be as if the request was unauthenticated with the addition of any other keys as defined by the auth type.

If the homeserver decides that an attempt on a stage was unsuccessful, but the client may make a second attempt, it returns the same HTTP status 401 response as above, with the addition of the standard errcode and error fields describing the error. For example:

HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
  "errcode": "M_FORBIDDEN",
  "error": "Invalid password",
  "completed": [ "example.type.foo" ],
  "flows": [
    {
      "stages": [ "example.type.foo", "example.type.bar" ]
    },
    {
      "stages": [ "example.type.foo", "example.type.baz" ]
    }
  ],
  "params": {
      "example.type.baz": {
          "example_key": "foobar"
      }
  },
  "session": "xxxxxx"
}

If the request fails for a reason other than authentication, the server returns an error message in the standard format. For example:

HTTP/1.1 400 Bad request
Content-Type: application/json
{
  "errcode": "M_EXAMPLE_ERROR",
  "error": "Something was wrong"
}

If the client has completed all stages of a flow, the homeserver performs the API call and returns the result as normal. Completed stages cannot be retried by clients, therefore servers must return either a 401 response with the completed stages, or the result of the API call if all stages were completed when a client retries a stage.

Some authentication types may be completed by means other than through the Matrix client, for example, an email confirmation may be completed when the user clicks on the link in the email. In this case, the client retries the request with an auth dict containing only the session key. The response to this will be the same as if the client were attempting to complete an auth state normally, i.e. the request will either complete or request auth, with the presence or absence of that auth type in the ‘completed’ array indicating whether that stage is complete.

A request to an endpoint that uses User-Interactive Authentication never succeeds without auth. Homeservers may allow requests that don’t require auth by offering a stage with only the m.login.dummy auth type, but they must still give a 401 response to requests with no auth data.

Example

At a high level, the requests made for an API call completing an auth flow with three stages will resemble the following diagram:

    _______________________
    |       Stage 0         |
    | No auth               |
    |  ___________________  |
    | |_Request_1_________| | <-- Returns "session" key which is used throughout.
    |_______________________|
             |
             |
    _________V_____________
    |       Stage 1         |
    | type: "<auth type1>"  |
    |  ___________________  |
    | |_Request_1_________| |
    |_______________________|
             |
             |
    _________V_____________
    |       Stage 2         |
    | type: "<auth type2>"  |
    |  ___________________  |
    | |_Request_1_________| |
    |  ___________________  |
    | |_Request_2_________| |
    |  ___________________  |
    | |_Request_3_________| |
    |_______________________|
             |
             |
    _________V_____________
    |       Stage 3         |
    | type: "<auth type3>"  |
    |  ___________________  |
    | |_Request_1_________| | <-- Returns API response
    |_______________________|
Authentication types

This specification defines the following auth types:

  • m.login.password
  • m.login.recaptcha
  • m.login.sso
  • m.login.email.identity
  • m.login.msisdn
  • m.login.dummy
  • m.login.registration_token
  • [Added in v1.11] m.login.terms
  • [Added in v1.17] m.oauth
Password-based
Type Description
m.login.password The client submits an identifier and secret password, both sent in plain-text.

To use this authentication type, clients should submit an auth dict as follows:

{
  "type": "m.login.password",
  "identifier": {
    ...
  },
  "password": "<password>",
  "session": "<session ID>"
}

where the identifier property is a user identifier object, as described in Identifier types.

For example, to authenticate using the user’s Matrix ID, clients would submit:

{
  "type": "m.login.password",
  "identifier": {
    "type": "m.id.user",
    "user": "<user_id or user localpart>"
  },
  "password": "<password>",
  "session": "<session ID>"
}

Alternatively reply using a 3PID bound to the user’s account on the homeserver using the /account/3pid API rather than giving the user explicitly as follows:

{
  "type": "m.login.password",
  "identifier": {
    "type": "m.id.thirdparty",
    "medium": "<The medium of the third-party identifier.>",
    "address": "<The third-party address of the user>"
  },
  "password": "<password>",
  "session": "<session ID>"
}

In the case that the homeserver does not know about the supplied 3PID, the homeserver must respond with 403 Forbidden.

Google ReCaptcha
Type Description
m.login.recaptcha The user completes a Google ReCaptcha 2.0 challenge.

To use this authentication type, clients should submit an auth dict as follows:

{
  "type": "m.login.recaptcha",
  "response": "<captcha response>",
  "session": "<session ID>"
}
Single Sign-On
Type Description
m.login.sso Authentication is supported by authorising with an external single sign-on provider.

A client wanting to complete authentication using SSO should use the Fallback mechanism. See SSO during User-Interactive Authentication for more information.

Email-based (identity / homeserver)
Type Description
m.login.email.identity Authentication is supported by authorising an email address with an identity server, or homeserver if supported.

Prior to submitting this, the client should authenticate with an identity server (or homeserver). After authenticating, the session information should be submitted to the homeserver.

To use this authentication type, clients should submit an auth dict as follows:

{
  "type": "m.login.email.identity",
  "threepid_creds": {
    "sid": "<identity server session id>",
    "client_secret": "<identity server client secret>",
    "id_server": "<url of identity server authed with, e.g. 'matrix.org:8090'>",
    "id_access_token": "<access token previously registered with the identity server>"
  },
  "session": "<session ID>"
}

Note that id_server (and therefore id_access_token) is optional if the /requestToken request did not include them.

Phone number/MSISDN-based (identity / homeserver)
Type Description
m.login.msisdn Authentication is supported by authorising a phone number with an identity server, or homeserver if supported.

Prior to submitting this, the client should authenticate with an identity server (or homeserver). After authenticating, the session information should be submitted to the homeserver.

To use this authentication type, clients should submit an auth dict as follows:

{
  "type": "m.login.msisdn",
  "threepid_creds": {
    "sid": "<identity server session id>",
    "client_secret": "<identity server client secret>",
    "id_server": "<url of identity server authed with, e.g. 'matrix.org:8090'>",
    "id_access_token": "<access token previously registered with the identity server>"
  },
  "session": "<session ID>"
}

Note that id_server (and therefore id_access_token) is optional if the /requestToken request did not include them.

Dummy Auth
Type Description
m.login.dummy Dummy authentication always succeeds and requires no extra parameters.

The purpose of dummy authentication is to allow servers to not require any form of User-Interactive Authentication to perform a request. It can also be used to differentiate flows where otherwise one flow would be a subset of another flow. e.g. if a server offers flows m.login.recaptcha and m.login.recaptcha, m.login.email.identity and the client completes the recaptcha stage first, the auth would succeed with the former flow, even if the client was intending to then complete the email auth stage. A server can instead send flows m.login.recaptcha, m.login.dummy and m.login.recaptcha, m.login.email.identity to fix the ambiguity.

To use this authentication type, clients should submit an auth dict with just the type and session, if provided:

{
  "type": "m.login.dummy",
  "session": "<session ID>"
}
Token-authenticated registration

[Added in v1.2]

Type Description
m.login.registration_token Registers an account with a pre-shared token for authentication

The m.login.registration_token authentication type is only valid on the /register endpoint.

This authentication type provides homeservers the ability to allow registrations to a limited set of people instead of either offering completely open registrations or completely closed registration (where the homeserver administrators create and distribute accounts).

The token required for this authentication type is shared out of band from Matrix and is an opaque string using the Opaque Identifier Grammar, with maximum length of 64 characters. The server can keep any number of tokens for any length of time/validity. Such cases might be a token limited to 100 uses or for the next 2 hours - after the tokens expire, they can no longer be used to create accounts.

To use this authentication type, clients should submit an auth dict with just the type, token, and session:

{
  "type": "m.login.registration_token",
  "token": "fBVFdqVE",
  "session": "<session ID>"
}

To determine if a token is valid before attempting to use it, the client can use the /validity API defined below. The API doesn’t guarantee that a token will be valid when used, but does avoid cases where the user finds out late in the registration process that their token has expired.

GET /_matrix/client/v1/register/m.login.registration_token/validity


Added in v1.2

Queries the server to determine if a given registration token is still valid at the time of request. This is a point-in-time check where the token might still expire by the time it is used.

Servers should be sure to rate limit this endpoint to avoid brute force attacks.

Rate-limited: Yes
Requires authentication: No

Request

Request parameters

query parameters
Name Type Description
token string

Required: The token to check validity of.


Responses

Status Description
200 The check has a result.
403 The homeserver does not permit registration and thus all tokens are considered invalid.
429 This request was rate-limited.

200 response

Name Type Description
valid boolean

Required: True if the token is still valid, false otherwise. This should additionally be false if the token is not a recognised token by the server.

{
  "valid": true
}

403 response

Error
Name Type Description
errcode string

Required: An error code.

error string

A human-readable error message.

{
  "errcode": "M_FORBIDDEN",
  "error": "Registration is not enabled on this homeserver."
}

429 response

RateLimitError
Name Type Description
errcode string

Required: The M_LIMIT_EXCEEDED error code

error string

A human-readable error message.

retry_after_ms integer

The amount of time in milliseconds the client should wait before trying the request again.

{
  "errcode": "M_LIMIT_EXCEEDED",
  "error": "Too many requests",
  "retry_after_ms": 2000
}
Terms of service at registration

[Added in v1.11]

Type Description
m.login.terms Authentication requires the user to accept a set of policy documents.

The m.login.terms authentication type is only valid on the /register endpoint.

This authentication type is used when the homeserver requires new users to accept a given set of policy documents, such as a terms of service and a privacy policy. There may be many different types of documents, all of which are versioned and presented in (potentially) multiple languages.

When the server requires the user to accept some terms, it does so by returning a 401 response to the /register request, where the response body includes m.login.terms in the flows list, and the m.login.terms property in the params object has the structure shown below.

If a client encounters an invalid parameter, registration should stop with an error presented to the user.

The client should present the user with a checkbox to accept each policy, including a link to the provided URL. Once the user has done so, the client submits an auth dict with just the type and session, as follows, to indicate that all of the policies have been accepted:

{
  "type": "m.login.terms",
  "session": "<session ID>"
}

The server is expected to track which document versions it presented to the user during registration, if applicable.

Example

  1. A client might submit a registration request as follows:

    POST /_matrix/client/v3/register
    
    {
      "username": "cheeky_monkey",
      "password": "ilovebananas"
    }
    
  2. The server requires the user to accept some terms of service before registration, so returns the following response:

    HTTP/1.1 401 Unauthorized
    Content-Type: application/json
    
    {
      "flows": [
        { "stages": [ "m.login.terms" ] }
      ],
      "params": {
        "m.login.terms": {
          "policies": {
            "terms_of_service": {
              "version": "1.2",
              "en": {
                  "name": "Terms of Service",
                  "url": "https://example.org/somewhere/terms-1.2-en.html"
              },
              "fr": {
                  "name": "Conditions d'utilisation",
                  "url": "https://example.org/somewhere/terms-1.2-fr.html"
              }
            }
          }
        }
      },
      "session": "kasgjaelkgj"
    }
    
  3. The client presents the list of documents to the user, inviting them to accept the polices.

  4. The client repeats the registration request, confirming that the user has accepted the documents:

    POST /_matrix/client/v3/register
    
    {
      "username": "cheeky_monkey",
      "password": "ilovebananas",
      "auth": {
        "type": "m.login.terms",
        "session": "kasgjaelkgj"
      }
    }
    
  5. All authentication steps have now completed, so the request is successful:

    HTTP/1.1 200 OK
    Content-Type: application/json
    
    {
      "access_token": "abc123",
      "device_id": "GHTYAJCE",
      "user_id": "@cheeky_monkey:matrix.org"
    }
    

m.login.terms params


Schema for m.login.terms entry in the params object in a User-Interactive Authentication response.

m.login.terms params
Name Type Description
policies {string: Policy Definition}

Required: A map from “Policy ID” to the current definition of this policy document. The Policy ID is a unique identifier for a given policy document, using the Opaque Identifier Grammar.

Policy Definition
Name Type Description
version string

Required: The version of this policy document. This is provided as a convenience for the client, and uses the Opaque Identifier Grammar.

<Other properties> Policy Translation

Map from language codes to details of the document in that language. Language codes SHOULD be formatted as per Section 2.2 of RFC 5646, though some implementations may use an underscore instead of dash (for example, en_US instead of en-US).

Policy Translation
Name Type Description
name string

Required: The name of this document, in the appropriate language. An arbitrary string with no specified maximum length.

url URI

Required: A link to the text of this document, in the appropriate language. MUST be a valid URI with scheme https:// or http://. Insecure HTTP is discouraged.

Examples

{
  "policies": {
    "privacy_policy": {
      "en": {
        "name": "Privacy Policy",
        "url": "https://example.org/somewhere/privacy-1.2-en.html"
      },
      "fr": {