When communicating with a 3rd Party REST API, it may be necessary to provide OAuth authentication. OAuth is an industry standard way of allowing two applications to talk to each other without having to share your username and password. In this case it means the 3rd party API has your credentials, but Hubitat Elevation will not.
The first step to supporting OAuth in your app is to enable it for the app code following the directions listed at: How to Install Custom Apps.
You will then need to create an access token done using createAccessToken()
. Calling this method will automatically store the access token in state.accessToken
.
You will next need to redirect the user to the API's OAuth endpoint. The URL should be provided by the vendor. Traditionally you will need to specify the following query string parameters:
response_type=code
client_id=valueProvidedByVendorAPI
scope=scopesAvailableInVendorAPI
redirect_uri=https://cloud.hubitat.com/oauth/stateredirect
state=urlPathToRedirectToAfterOAuth
The value of state should be set to a webservice endpoint in your App (defined using mappings
). The value will look like: ${getHubUID()}/apps/${app.id}/yourWebserviceNameHere?access_token=${state.accessToken}
After the user authorizes your App through the vendor's website, they will be redirected to your URL so that you can continue the OAuth process.
At this point you will need to request the OAuth token. This is done, usually, via a POST method to an API endpoint provided by the vendor. Traditionally, you will pass the following in the body or query string, depending on the vendor:
grant_type=authorization_code
code=authCodePassedInQueryStringToWebserviceMethod
client_id=valueProvidedByVendorAPI
redirect_uri=https://cloud.hubitat.com/oauth/stateredirect
Consult the vendor's API documentation for the exact parameters.
At this point you will receive a result that includes both the token and your refresh token. Consult the vendor's documentation for information on how frequently you must refresh the token and how to supply the token to each REST API call.