-
Notifications
You must be signed in to change notification settings - Fork 381
/
client_server_api.rst
2143 lines (1635 loc) · 80.7 KB
/
client_server_api.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.. Copyright 2016-2020 The Matrix.org Foundation C.I.C.
..
.. Licensed under the Apache License, Version 2.0 (the "License");
.. you may not use this file except in compliance with the License.
.. You may obtain a copy of the License at
..
.. http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing, software
.. distributed under the License is distributed on an "AS IS" BASIS,
.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.. See the License for the specific language governing permissions and
.. limitations under the License.
Client-Server API
=================
{{unstable_warning_block_CLIENT_RELEASE_LABEL}}
The client-server API provides a simple lightweight API to let clients 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.
.. contents:: Table of Contents
.. sectnum::
Changelog
---------
.. topic:: Version: %CLIENT_RELEASE_LABEL%
{{client_server_changelog}}
This version of the specification is generated from
`matrix-doc <https://github.com/matrix-org/matrix-doc>`_ as of Git commit
`{{git_version}} <https://github.com/matrix-org/matrix-doc/tree/{{git_rev}}>`_.
For the full historical changelog, see
https://github.com/matrix-org/matrix-doc/blob/master/changelogs/client_server.rst
Other versions of this specification
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following other versions are also available, in reverse chronological order:
- `HEAD <https://matrix.org/docs/spec/client_server/unstable.html>`_: Includes all changes since the latest versioned release.
- `r0.6.1 <https://matrix.org/docs/spec/client_server/r0.6.1.html>`_
- `r0.6.0 <https://matrix.org/docs/spec/client_server/r0.6.0.html>`_
- `r0.5.0 <https://matrix.org/docs/spec/client_server/r0.5.0.html>`_
- `r0.4.0 <https://matrix.org/docs/spec/client_server/r0.4.0.html>`_
- `r0.3.0 <https://matrix.org/docs/spec/client_server/r0.3.0.html>`_
- `r0.2.0 <https://matrix.org/docs/spec/client_server/r0.2.0.html>`_
- `r0.1.0 <https://matrix.org/docs/spec/client_server/r0.1.0.html>`_
- `r0.0.1 <https://matrix.org/docs/spec/r0.0.1/client_server.html>`_
- `r0.0.0 <https://matrix.org/docs/spec/r0.0.0/client_server.html>`_
- `Legacy <https://matrix.org/docs/spec/legacy/#client-server-api>`_: The last draft before the spec was formally released in version r0.0.0.
API Standards
-------------
.. TODO: Move a lot of this to a common area for all specs.
.. TODO
Need to specify any HMAC or access_token lifetime/ratcheting tricks
We need to specify capability negotiation for extensible transports
The mandatory baseline for client-server communication in Matrix is exchanging
JSON objects over HTTP APIs. HTTPS is recommended for communication, although
HTTP may be supported as a fallback to support basic
HTTP clients. More efficient optional transports
will in future be supported as optional extensions - e.g. a
packed binary encoding over stream-cipher encrypted TCP socket for
low-bandwidth/low-roundtrip mobile usage. For the default HTTP transport, all
API calls use a Content-Type of ``application/json``. In addition, all strings
MUST be encoded as UTF-8. Clients are authenticated using opaque
``access_token`` strings (see `Client Authentication`_ for details), passed as a
query string parameter on all requests.
The names of the API endpoints for the HTTP transport follow a convention of
using underscores to separate words (for example ``/delete_devices``). The key
names in JSON objects passed over the API also follow this convention.
.. NOTE::
There are a few historical exceptions to this rule, such as
``/createRoom``. A future version of this specification will address the
inconsistency.
Any errors which occur at the Matrix API level MUST return a "standard error
response". This is a JSON object which looks like:
.. code:: json
{
"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``. These error
codes should have their namespace first in ALL CAPS, followed by a single _ to
ease separating the namespace from the error code. 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``. There may be additional keys depending on the
error, 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.
The common error codes are:
:``M_FORBIDDEN``:
Forbidden access, e.g. joining a room without permission, failed login.
:``M_UNKNOWN_TOKEN``:
The access 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 <#soft-logout>`_ for more
information.
:``M_MISSING_TOKEN``:
No access token was specified for the request.
:``M_BAD_JSON``:
Request contained valid JSON, but it was malformed in some way, e.g. missing
required keys, invalid values for keys.
:``M_NOT_JSON``:
Request did not contain valid JSON.
:``M_NOT_FOUND``:
No resource was found for this request.
:``M_LIMIT_EXCEEDED``:
Too many requests have been sent in a short period of time. Wait a while then
try again.
:``M_UNKNOWN``:
An unknown error has occurred.
Other error codes the client might encounter are:
:``M_UNRECOGNIZED``:
The server did not understand the request.
:``M_UNAUTHORIZED``:
The request was not correctly authorized. Usually due to login failures.
:``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.
:``M_INVALID_USERNAME``:
Encountered when trying to register a user ID which is not valid.
:``M_ROOM_IN_USE``:
Sent when the room alias given to the ``createRoom`` API is already in use.
:``M_INVALID_ROOM_STATE``:
Sent when the initial state given to the ``createRoom`` API is invalid.
:``M_THREEPID_IN_USE``:
Sent when a threepid given to an API cannot be used because the same threepid is already in use.
:``M_THREEPID_NOT_FOUND``:
Sent when a threepid given to an API cannot be used because no record matching the threepid was found.
:``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_SERVER_NOT_TRUSTED``:
The client's request used a third party server, eg. identity server, that this server does not trust.
:``M_UNSUPPORTED_ROOM_VERSION``:
The client's request to create a room used a room version that the server does not support.
:``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_BAD_STATE``:
The state change requested cannot be performed, such as attempting to unban
a user who is not banned.
:``M_GUEST_ACCESS_FORBIDDEN``:
The room or resource does not permit guests to access it.
:``M_CAPTCHA_NEEDED``:
A Captcha is required to complete the request.
:``M_CAPTCHA_INVALID``:
The Captcha provided did not match what was expected.
:``M_MISSING_PARAM``:
A required parameter was missing from the request.
:``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_TOO_LARGE``:
The request or entity was too large.
:``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_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 (eg: sending messages, account data, etc) and not routes which only
read state (eg: ``/sync``, get account data, etc).
:``M_CANNOT_LEAVE_SERVER_NOTICE_ROOM``:
The user is unable to reject an invite to join the server notices room. See the
`Server Notices <#server-notices>`_ module for more information.
.. TODO: More error codes (covered by other issues)
.. * M_CONSENT_NOT_GIVEN - GDPR: https://github.com/matrix-org/matrix-doc/issues/1512
.. _sect:txn_ids:
The client-server API typically uses ``HTTP PUT`` to submit requests with a
client-generated transaction identifier. This means that these requests are
idempotent. The scope of a transaction identifier is a particular access token.
It **only** serves to identify new
requests from retransmits. After the request has finished, the ``{txnId}``
value should be changed (how is not specified; a monotonically increasing
integer is recommended).
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.
{{versions_cs_http_api}}
.. _`CORS`:
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 s
upport 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:
.. code::
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
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 URI
~~~~~~~~~~~~~~
.. Note::
Servers hosting the ``.well-known`` JSON file SHOULD offer CORS headers, as
per the `CORS`_ section in this specification.
The ``.well-known`` method uses a JSON file at a predetermined location to
specify parameter values. The flow for this method 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.
3. Make a GET request to ``https://hostname/.well-known/matrix/client``.
a. If the returned status code is 404, then ``IGNORE``.
b. If the returned status code is not 200, or the response body is empty,
then ``FAIL_PROMPT``.
c. Parse the response body as a JSON object
i. If the content cannot be parsed, then ``FAIL_PROMPT``.
d. Extract the ``base_url`` value from the ``m.homeserver`` property. This
value is to be used as the base URL of the homeserver.
i. If this value is not provided, then ``FAIL_PROMPT``.
e. Validate the homeserver base URL:
i. Parse it as a URL. If it is not a URL, then ``FAIL_ERROR``.
ii. 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.
f. 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/api/v1`` as the endpoint to connect to. If the
``m.identity_server`` property is present, but does not have a
``base_url`` value, then ``FAIL_ERROR``.
{{wellknown_cs_http_api}}
Client Authentication
---------------------
Most API endpoints require the user to identify themselves by presenting
previously obtained credentials in the form of an ``access_token`` query
parameter or through an Authorization Header of ``Bearer $access_token``.
An access token is typically obtained via the `Login`_ or `Registration`_ processes.
.. NOTE::
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 <macaroon_>`_.
Using access tokens
~~~~~~~~~~~~~~~~~~~
Access tokens may be provided in two ways, both of which the homeserver MUST
support:
1. Via a query string parameter, ``access_token=TheTokenHere``.
#. Via a request header, ``Authorization: Bearer TheTokenHere``.
Clients are encouraged to use the ``Authorization`` header where possible
to prevent the access token being leaked in access/HTTP logs. The query
string should only be used in cases where the ``Authorization`` header is
inaccessible for the client.
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.
Relationship between access tokens and devices
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Client `devices`_ are closely related to access tokens. Matrix servers should
record which device each access token is assigned to, so that subsequent
requests can be handled correctly.
By default, the `Login`_ and `Registration`_ processes auto-generate a new
``device_id``. A client is also free to generate its own ``device_id`` or,
provided the user remains the same, reuse a device: in either case the client
should pass the ``device_id`` in the request body. If the client sets the
``device_id``, the server will invalidate any access token previously assigned
to that device. There is therefore at most one active access token assigned to
each device at any one time.
Soft logout
~~~~~~~~~~~
When a request fails due to a 401 status code per above, the server can
include an extra response parameter, ``soft_logout``, to indicate if the client's
persisted information can be retained. This defaults to ``false``, indicating
that the server has destroyed the session. Any persisted state held by the client,
such as encryption keys and device information, must not be reused and must be discarded.
When ``soft_logout`` is true, the client can acquire a new access token by
specifying the device ID it is already using to the login API. In most cases
a ``soft_logout: true`` response indicates that the user's session has expired
on the server-side and the user simply needs to provide their credentials again.
In either case, the client's previously known access token will no longer function.
.. _`user-interactive authentication`:
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 social network (OAuth2),
login by confirming a token sent to their email address, 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 login 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:
.. code::
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:
.. code::
POST /_matrix/client/r0/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:
.. code::
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:
.. code::
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:
.. code::
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.oauth2``
- ``m.login.sso``
- ``m.login.email.identity``
- ``m.login.msisdn``
- ``m.login.token``
- ``m.login.dummy``
Password-based
<<<<<<<<<<<<<<
:Type:
``m.login.password``
:Description:
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:
.. code:: json
{
"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:
.. code:: json
{
"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 then giving the ``user`` explicitly as
follows:
.. code:: json
{
"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:
``m.login.recaptcha``
:Description:
The user completes a Google ReCaptcha 2.0 challenge
To use this authentication type, clients should submit an auth dict as follows:
.. code:: json
{
"type": "m.login.recaptcha",
"response": "<captcha response>",
"session": "<session ID>"
}
Token-based
<<<<<<<<<<<
:Type:
``m.login.token``
:Description:
The client submits a login token.
To use this authentication type, clients should submit an auth dict as follows:
.. code:: json
{
"type": "m.login.token",
"token": "<token>",
"txn_id": "<client generated nonce>",
"session": "<session ID>"
}
A client may receive a login ``token`` via some external service, such as email
or SMS. Note that a login token is separate from an access token, the latter
providing general authentication to various API endpoints.
Additionally, the server must encode the user ID in the ``token``; there is
therefore no need for the client to submit a separate username.
The ``txn_id`` should be a random string generated by the client for the
request. The same ``txn_id`` should be used if retrying the request. The
``txn_id`` may be used by the server to disallow other devices from using the
token, thus providing "single use" tokens while still allowing the device to
retry the request. This would be done by tying the token to the ``txn_id``
server side, as well as potentially invalidating the token completely once the
device has successfully logged in (e.g. when we receive a request from the
newly provisioned access_token).
OAuth2-based
<<<<<<<<<<<<
:Type:
``m.login.oauth2``
:Description:
Authentication is supported via OAuth2 URLs. This login consists of multiple
requests.
:Parameters:
``uri``: Authorization Request URI OR service selection URI. Both contain an
encoded ``redirect URI``.
The homeserver acts as a 'confidential' client for the purposes of OAuth2. If
the uri is a ``service selection URI``, it MUST point to a webpage which prompts
the user to choose which service to authorize with. On selection of a service,
this MUST link through to an ``Authorization Request URI``. If there is only one
service which the homeserver accepts when logging in, this indirection can be
skipped and the "uri" key can be the ``Authorization Request URI``.
The client then visits the ``Authorization Request URI``, which then shows the
OAuth2 Allow/Deny prompt. Hitting 'Allow' redirects to the ``redirect URI`` with
the auth code. Homeservers can choose any path for the ``redirect URI``. Once
the OAuth flow has completed, the client retries the request with the session
only, as above.
Single Sign-On
<<<<<<<<<<<<<<
:Type:
``m.login.sso``
:Description:
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:
``m.login.email.identity``
:Description:
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:
.. code:: json
{
"type": "m.login.email.identity",
"threepidCreds": [
{
"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:
``m.login.msisdn``
:Description:
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:
.. code:: json
{
"type": "m.login.msisdn",
"threepidCreds": [
{
"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:
``m.login.dummy``
:Description:
Dummy authentication always succeeds and requires no extra parameters. Its
purpose 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. eg. 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:
.. code:: json
{
"type": "m.login.dummy",
"session": "<session ID>"
}
Fallback
++++++++
Clients cannot be expected to be able to know how to process every single login
type. If a client does not know how to handle a given login type, it can direct
the user to a web browser with the URL of a fallback page which will allow the
user to complete that login step out-of-band in their web browser. The URL it
should open is::
/_matrix/client/%CLIENT_MAJOR_VERSION%/auth/<auth type>/fallback/web?session=<session ID>
Where ``auth type`` is the type name of the stage it is attempting and
``session ID`` is the ID of the session given by the homeserver.
.. _`user-interactive authentication fallback completion`:
This MUST return an HTML page which can perform this authentication stage. This
page must use the following JavaScript when the authentication has been
completed:
.. code:: javascript
if (window.onAuthDone) {
window.onAuthDone();
} else if (window.opener && window.opener.postMessage) {
window.opener.postMessage("authDone", "*");
}
This allows the client to either arrange for the global function ``onAuthDone``
to be defined in an embedded browser, or to use the HTML5 `cross-document
messaging <https://www.w3.org/TR/webmessaging/#web-messaging>`_ API, to receive
a notification that the authentication stage has been completed.
Once a client receives the notificaton that the authentication stage has been
completed, it should resubmit the request with an auth dict with just the
session ID:
.. code:: json
{
"session": "<session ID>"
}
Example
<<<<<<<
A client webapp might use the following javascript to open a popup window which will
handle unknown login types:
.. code:: javascript
/**
* Arguments:
* homeserverUrl: the base url of the homeserver (eg "https://matrix.org")
*
* apiEndpoint: the API endpoint being used (eg
* "/_matrix/client/%CLIENT_MAJOR_VERSION%/account/password")
*
* loginType: the loginType being attempted (eg "m.login.recaptcha")
*
* sessionID: the session ID given by the homeserver in earlier requests
*
* onComplete: a callback which will be called with the results of the request
*/
function unknownLoginType(homeserverUrl, apiEndpoint, loginType, sessionID, onComplete) {
var popupWindow;
var eventListener = function(ev) {
// check it's the right message from the right place.
if (ev.data !== "authDone" || ev.origin !== homeserverUrl) {
return;
}
// close the popup
popupWindow.close();
window.removeEventListener("message", eventListener);
// repeat the request
var requestBody = {
auth: {
session: sessionID,
},
};
request({
method:'POST', url:apiEndpint, json:requestBody,
}, onComplete);
};
window.addEventListener("message", eventListener);