-
Notifications
You must be signed in to change notification settings - Fork 19
OAuth
The access token given in the Monzo Developer Playground will expire after a short period of a few hours. For applications integrating monzo-python which need access to the Monzo API for longer periods, you will need to use a OAuth session.
In order to get OAuth credentials for monzo-python:
-
Head to the Clients Section of the developer playground.
-
Click "New OAuth Client".
-
Give your client a name, e.g. "MyApplication".
-
Enter the "Redirect URL" as the URL on which MyApplication will listen for an authentication code.
e.g.
http://[MyApplication URL]/api/monzo/callback
-
Select "Confidential" from the Confidentiality dropdown box.
-
Click "Submit" and make a note of the newly created client id and secret, you will need this for your Home Assistant configuration.
Note: If your application doesn't include a http server which can pass the authentication code sent to the redirect url on to monzo-python, you can enter it as http://localhost
and omit it from the following code.
To use a proper OAuth session in monzo-python we need to use the MonzoOAuth2Client class.
from monzo import MonzoOAuth2Client # Import OAuth client class
oauth_client = MonzoOAuth2Client('client_id', 'client_secret',redirect_uri='redirect_url') # Replace with details entered on developer playground.
auth_start_url = oauth_client.authorize_token_url() # Returns a dictionary containing the Monzo authentication startpoint.
After authentication, Monzo will send the user an email containing a "magic link" to the redirect url you entered on the developer website. This url is appended with the authentication code which needs to be exchanged for an access token.
If your application includes a http server you may wish to add a handler to automatically pass the authentication code back to your MonzoOAuth2Client
. Otherwise the user can extract the authentication code from the url and enter it manually.
oauth_client.fetch_access_token('authentication_code_from_magic_link')
At this point the OAuth session is complete and oauth_client
will automatically refresh tokens as they expire.
To interact with the Monzo API we then insert our oauth_client
into a Monzo
object
from monzo import Monzo # Import Monzo class
client = Monzo.from_oauth_session(oauth_client)
By default the OAuth client token is automatically saved to the file monzo.json
. If you want need to store this elsewhere in your application, this can be done by initialising MonzoOAuth2Client
with the optional argument refresh_callback
being the function handling updating token storage.