Skip to content

Commit e161ab7

Browse files
committed
Added getting started and authentication page
1 parent 01f8e46 commit e161ab7

File tree

3 files changed

+402
-0
lines changed

3 files changed

+402
-0
lines changed

docs/index.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,8 @@ There are several ways to support Mautic other than contributing with code.
147147
:caption: REST API
148148
:hidden:
149149

150+
rest_api/getting_started
151+
rest_api/authentication
150152
rest_api/assets
151153
rest_api/campaigns
152154
rest_api/categories

docs/rest_api/authentication.rst

Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
Authentication
2+
##############
3+
4+
Mautic supports OAuth2 or Basic Authentication for API authentication.
5+
6+
Basic authentication
7+
********************
8+
9+
To get started quickly with Mautic's API, you can use Basic Authentication.
10+
11+
.. note::
12+
13+
Mautic recommends OAuth2 for security reasons. If you still want to use Basic Authentication, you must first enable it in ``Configuration -> API Settings`` in the Mautic UI, or by setting ``'api_enable_basic_auth' => true`` in ``app/config/local.php`` directly.
14+
15+
After enabling Basic Authentication, you can use it in Mautic's API as follows:
16+
17+
Using Mautic's API library with ``BasicAuth``
18+
=============================================
19+
20+
.. code-block:: php
21+
22+
<?php
23+
24+
use GuzzleHttp\Client;
25+
use Mautic\Auth\ApiAuth;
26+
use Mautic\MauticApi;
27+
28+
// Initiate an HTTP Client
29+
$httpClient = new Client([
30+
'timeout' => 10,
31+
]);
32+
33+
// Initiate the auth object
34+
$settings = [
35+
'userName' => 'YOUR_USERNAME',
36+
'password' => 'YOUR_PASSWORD'
37+
];
38+
$apiUrl = 'https://mautic.example.com';
39+
40+
$initAuth = new ApiAuth($httpClient);
41+
$auth = $initAuth->newAuth($settings, 'BasicAuth');
42+
43+
$api = new MauticApi();
44+
$contactsApi = $api->newApi('contacts', $auth, $apiUrl);
45+
$contacts = $contactsApi->getList();
46+
47+
.. vale off
48+
49+
Plain HTTP requests
50+
===================
51+
52+
.. vale on
53+
54+
1. Combine the username and password of a Mautic User with a colon ``:``. For example, ``user:password``.
55+
2. Base64 encode this value. For example, with ``echo -n 'user:password' | base64``. This outputs something like ``dXNlcjpwYXNzd29yZA==``.
56+
3. Add an Authorization header to each API request as ``Authorization: Basic dXNlcjpwYXNzd29yZA==``
57+
58+
Here's an example:
59+
60+
.. code-block:: console
61+
62+
curl -H "Authorization: Basic dXNlcjpwYXNzd29yZA==" https://mautic.example.com/api/contacts
63+
64+
OAuth2
65+
******
66+
67+
After enabling Mautic's API, the "API Credentials" menu item shows up in the administrator menu. You can create Client ID and Secret there, which you can then use in the next steps.
68+
69+
.. note::
70+
71+
Mautic supports the ``authorization_code``, ``refresh_token`` and ``client_credentials`` grant types.
72+
73+
There are two main flows that Mautic supports:
74+
75+
.. list-table::
76+
:header-rows: 1
77+
78+
* - Name
79+
- Description
80+
* - Authorization code flow
81+
- This flow is best if you want Users to log in with their own Mautic accounts. All actions taken get registered as if the User performed them in Mautic's UI.
82+
* - Client Credentials flow
83+
- This flow is best for Machine-to-Machine, M2M, communications. For example, in cron jobs that run on at fixed times of the day.
84+
All actions get registered under the name that you provided in ``Settings > API Credentials``.
85+
So if you called your API Credential ``Mautibot test``, Contacts created through the API show up as ``Contact was identified by Mautibot test [1]``, where ``[1]`` is the ID of the API Credential.
86+
87+
88+
Authorization code flow
89+
========================
90+
91+
Using Mautic's API library for the Authorization Code flow
92+
----------------------------------------------------------
93+
94+
Mautic's API library has built-in support for the OAuth2 Authorization Code flow. You can use it as follows:
95+
96+
.. code-block:: php
97+
98+
<?php
99+
100+
use Mautic\Auth\ApiAuth;
101+
102+
// This is needed for the API library to store the OAuth2 state in the $_SESSION
103+
session_start();
104+
105+
// $initAuth->newAuth() will accept an array of OAuth settings
106+
$settings = array(
107+
'baseUrl' => 'https://mautic.example.com',
108+
'version' => 'OAuth2',
109+
'clientKey' => '5ad6fa7asfs8fa7sdfa6sfas5fas6asdf8', // A Client Key can be created in Mautic's UI through the "API Credentials" menu item
110+
'clientSecret' => 'adf8asf7sf54asf3as4f5sf6asfasf97dd', // A Client Secret can be created in Mautic's UI through the "API Credentials" menu item
111+
'callback' => 'https://example.com/your-callback'
112+
);
113+
114+
// Initiate the auth object
115+
$initAuth = new ApiAuth();
116+
$auth = $initAuth->newAuth($settings, 'OAuth');
117+
118+
// Initiate process for obtaining an access token; this method will redirect the user to the authorize endpoint and/or set the tokens when the user is redirected back after granting authorization
119+
if ($auth->validateAccessToken()) {
120+
if ($auth->accessTokenUpdated()) {
121+
$accessTokenData = $auth->getAccessTokenData();
122+
123+
// store the access token data however you want
124+
}
125+
}
126+
127+
Using plain OAuth2 for the Authorization Code flow
128+
--------------------------------------------------
129+
130+
.. note::
131+
132+
The OAuth processes can be tricky. If possible, it's best to use an OAuth library for the language that's used. If you're using PHP, Mautic recommends using the :xref:`Mautic API Library`.
133+
134+
Step one - obtain authorization code
135+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
136+
137+
Redirect the User to the authorize endpoint ``/oauth/v2/authorize``:
138+
139+
.. code-block:: console
140+
141+
# NOTE: navigate to this URL in the browser as it renders the login form
142+
https://mautic.example.com/oauth/v2/authorize?grant_type=authorization_code
143+
&client_id=CLIENT_ID
144+
&redirect_uri=https%3A%2F%2Fexample.com%2Fyour-callback
145+
&response_type=code
146+
&state=UNIQUE_STATE_STRING
147+
148+
(note that the query has been wrapped for legibility)
149+
150+
.. note::
151+
152+
The state is optional but recommended to prevent ``CSRF`` attacks. It should be a uniquely generated string and stored locally in a session, cookie, etc. so you can compare it with the returned value.
153+
154+
.. note::
155+
156+
Note that the ``redirect_uri`` should be URL encoded.
157+
158+
This prompts the User to login. Once they do, Mautic redirects them back to the URL specified in the ``redirect_uri`` with a code appended to the query.
159+
160+
It may look something like: ``https://example.com/your-callback?code=UNIQUE_CODE_STRING&state=UNIQUE_STATE_STRING``
161+
162+
You should compare the returned ``state`` against the original to ensure the request wasn't tampered with.
163+
164+
Step two - replace with an access token
165+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
166+
167+
Obtain the value of the code from Step One, then immediately POST it back to the access token endpoint ``oauth/v2/token`` like so:
168+
169+
.. code-block:: console
170+
171+
curl -X POST \
172+
-H "Content-Type: application/x-www-form-urlencoded" \
173+
-d "grant_type=authorization_code&client_id=CLIENT_ID&redirect_uri=https%3A%2F%2Fexample.com%2Fyour-callback&client_secret=CLIENT_SECRET&code=UNIQUE_CODE_STRING" \
174+
https://mautic.example.com/oauth/v2/token
175+
176+
The response returned is a JSON encoded string:
177+
178+
.. code-block:: json
179+
180+
{
181+
"access_token": "ACCESS_TOKEN",
182+
"expires_in": 3600,
183+
"token_type": "bearer",
184+
"scope": "",
185+
"refresh_token": "REFRESH_TOKEN"
186+
}
187+
188+
Please store this data in a secure location and use it to authenticate API requests.
189+
190+
Refreshing tokens
191+
^^^^^^^^^^^^^^^^^
192+
193+
The response's ``expires_in`` is the number of seconds the access token is good for and may differ based on what you configured in Mautic. The code handling the authorization process should generate an expiration timestamp based on that value. For example ``<?php $expiration = time() + $response['expires_in']; ?>``. If the access token has expired, you can use the ``refresh_token`` to obtain a new access token.
194+
195+
By default, the refresh token is valid for 14 days unless configured otherwise in Mautic.
196+
197+
* If your app requests a new access token using the refresh token within 14 days, there's no need for any User interaction. Your app gets both a new access token and a new refresh token, which is valid for another 14 days after it's issued;
198+
* If your app doesn't request a new token using the refresh token within 14 days, you'll need to start from Step One again and redirect the User to Mautic's login.
199+
200+
The refresh token's expiration time is configurable through Mautic's Configuration.
201+
202+
.. note::
203+
The app should monitor for a ``400 Bad Request`` response when requesting a new access token and redirect the User back through the authorization process if that happens.
204+
205+
To obtain a new access token, you should do a POST call to the access token's endpoint ``oauth/v2/token`` using the ``refresh_token`` grant type, like so:
206+
207+
.. code-block:: console
208+
209+
curl -X POST \
210+
-H "Content-Type: application/x-www-form-urlencoded" \
211+
-d "grant_type=refresh_token&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&refresh_token=REFRESH_TOKEN" \
212+
https://mautic.example.com/oauth/v2/token
213+
214+
The response returned should be a JSON encoded string:
215+
216+
.. code-block:: json
217+
218+
{
219+
"access_token": "NEW_ACCESS_TOKEN",
220+
"expires_in": 3600,
221+
"token_type": "bearer",
222+
"scope": "",
223+
"refresh_token": "REFRESH_TOKEN"
224+
}
225+
226+
.. vale off
227+
228+
Client Credentials flow
229+
=======================
230+
231+
Using Mautic's API library for the Client Credentials flow
232+
----------------------------------------------------------
233+
234+
.. vale on
235+
236+
.. warning::
237+
238+
Mautic's API library doesn't have support yet for this flow, but there's an open PR that adds support: https://github.com/mautic/api-library/pull/269
239+
240+
.. vale off
241+
242+
Using plain OAuth2 for the Client Credentials flow
243+
--------------------------------------------------
244+
245+
.. vale on
246+
247+
To obtain a new access token, make a POST request to the access token's endpoint ``oauth/v2/token`` using the ``client_credentials`` grant type.
248+
249+
.. code-block:: console
250+
251+
curl -X POST \
252+
-H "Content-Type: application/x-www-form-urlencoded" \
253+
-d "grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET" \
254+
https://mautic.example.com/oauth/v2/token
255+
256+
The response returned should be a JSON encoded string:
257+
258+
.. code-block:: json
259+
260+
{
261+
"access_token": "NEW_ACCESS_TOKEN",
262+
"expires_in": 3600,
263+
"token_type": "bearer",
264+
"scope": ""
265+
}
266+
267+
.. vale off
268+
269+
Authenticating the API Request
270+
==============================
271+
272+
.. vale on
273+
274+
Authenticating the API request with OAuth2 is easy. Choose one of the following methods that's appropriate for the app's needs.
275+
276+
Authorization header
277+
--------------------
278+
279+
By using an authorization header, you can authenticate against all of Mautic's API endpoints.
280+
281+
However, note that this method requires that your Mautic server can pass headers to PHP or has access to the ``apache_request_headers()`` function. ``apache_request_headers()`` isn't available to PHP running under FastCGI.
282+
283+
.. code-block:: console
284+
285+
Authorization: Bearer ACCESS_TOKEN
286+
287+
Other methods
288+
-------------
289+
290+
You can also append the access token to the query or include it the POST body, but only when using ``x-www-form-unencoded``.
291+
292+
.. code-block:: console
293+
294+
GET https://mautic.example.com/api/leads?access_token=ACCESS_TOKEN
295+
296+
.. code-block:: console
297+
298+
curl -X POST \
299+
-H "Content-Type: application/x-www-form-urlencoded" \
300+
-d "firstname=John&lastname=Smith&access_token=ACCESS_TOKEN" \
301+
https://mautic.example.com.com/api/leads/new

0 commit comments

Comments
 (0)