Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mystix/424557e55e53df12099a66242270c643 to your computer and use it in GitHub Desktop.
Save mystix/424557e55e53df12099a66242270c643 to your computer and use it in GitHub Desktop.
Xero client_credentials workaround - January 2020
Here is a workaround for the lack of a client credentials flow in Xero's OAuth 2.0 / OpenID Connect implementation.
From Xero's FAQ: https://developer.xero.com/faq/all/oauth-private
"Is there an equivalent of two-legged private apps in OAuth 2.0?
No, all users will follow the same OAuth 2.0 code flow.
Once you have an access token and refresh token you can refresh indefinitely or until the token is revoked by the user."
Workaround:
1. Login to Xero as the Xero user to use for the machine-to-machine flow workaround.
2. Configure your App to have a redirect URI of: http://localhost
3. In a new tab in your browser, browse to:
https://login.xero.com/identity/connect/authorize?response_type=code&client_id=[YOUR_CLIENT_ID]&redirect_uri=http://localhost&scope=offline_access openid profile email accounting.transactions&state=123
Note: Ensure you specify all the scopes you need for the API calls your app will make.
4. Accept and give consent for your app
5. The browser is redirected to:
http://localhost/?code=[YOUR_CODE]&scope=openid%20profile%20email%20accounting.transactions&state=123&session_state=[BLAH]
6. Extract code parameter from the browser's URL.
7. Exchange the code for tokens
As per section "3. Exchange the Code" in https://developer.xero.com/documentation/oauth2/auth-flow, POST the code to https://identity.xero.com/connect/token
e.g.
curl --location --request POST 'https://identity.xero.com/connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic [YOUR_BASE64_CLIENTID:CLIENTSECRET]' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'redirect_uri=http://localhost' \
--data-urlencode 'code=[YOUR_CODE]'
NOTE: the code expires after approximately 1 minute.
8. Now you have the first Access and Refresh Token that you can securely store server-side in your app or a secure vault.
9. Your app will need to refresh the Tokens before the Access Token expires every 30 minutes - and store the new Access and Refresh Tokens that are received from that refresh POST - as per the section "Refreshing access tokens" in https://developer.xero.com/documentation/oauth2/auth-flow.
10. Call the Connections API in order to identify the Tenant Id that you need to use when calling each API.
GET https://api.xero.com/connections
You need to set the Authorization header the [Bearer] Access Token .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment