Tasker & Long Lived Access Tokens

Hi. I’m hoping someone can help me to understand the new Long Lived Access Tokens better and how to make them work with Tasker.

Currently, I use the Legacy API Password with Tasker to interact with Home Assistant for a few entities and it works perfectly. One example of the working (legacy api) method which will toggle my living room light follows:
**Note: %HASSIO_SERVER & %HA_LEGACY_API_KEY are variables

  • Create task
  • Add action > HTTP Post
Server:Port
%HASSIO_SERVER/api/services/switch/toggle?api_password=%HA_LEGACY_API_KEY

Data / File
{ "entity_id": "switch.living_room_light" }

Content Type
application/json

I cannot seem to get anywhere with the Long Lived Access Token method of authentication. :frowning_face: I have tried multiple variations in the URL construction but the closest I can get is no error returned in Tasker and a

Login attempt or request with invalid authentication from 192.168.1.1

error in the Home Assistant log.

Any assistance or insight would be appreciated.

1 Like

From the docs it says the token must be passed through in a header, google says its not possible to do inside a url. So might need to see if tasker let’s your set headers, just checked and IFTTT(webhooks) doesn’t as far as I could see

So this means we won’t be able to control it over tasker?

I upgraded yesterday and my current method that worked previously no longer works, I just get the failed login attempt card appear in the front end.

It would suck if we can’t sort this out…

I had to get up this morning in the dark and turn on my own kettle after dismissing my alarm, I felt like a caveman… :frowning:

@dshokouhi found a plugin for tasker.

For those who want to check out Long-Lived Access Tokens in 0.78 here are the steps I found for tasker, download this tasker plugin: https://play.google.com/store/apps/details?id=com.freehaha.restask&hl=en_US then setup a task for it inside tasker. Once you start creating the task setup the HTTP Post just like you did before under the Settings tab…Request Type becomes POST, Host is the full API URL (ex: https://hassurl:port/api/services/script/turn_on …notice how api_password is not there) scroll down and check Enable Custom Body then under Custom Body put the JSON (service data) you want to pass…then slide over to the right for Headers…Add a header and call the Name Authorization then for Value you want Bearer <token> where <token> is the long-lived access token that you created under the profile in 0.78…the task should work once you have that setup

9 Likes

@awarecan
Thank you very much for linking that post. I had previously tried RESTask unsuccessfully but following those instructions worked perfectly!
I can now convert my existing Tasker tasks to using the Long Lived Access Token and disable the Legacy API Password in Hass.io without losing any functionality. :smile:

Thanks again for all you do helping the HA community!

How do you guys generate the token? In the frontend?

In your profile panel, https://hassbian.local:8123/profile

4 Likes

Thanks, didn’t realise that page existed :slight_smile:

This post reminded me to move various Tasker profiles from legacy API password to Access Tokens.

I was able to get them working without using a plugin through use of a JavaScriptlet - a redacted exported description of my task that signals HASS that I’ve woken up in the morning is below in case it is of use (or in case I forget and wind up searching on this in the future).

RunScript (40)
A1: Variable Set [ Name:%url To:http://IPADDRESS:PORT Recurse Variables:Off Do Maths:Off Append:Off ] 
A2: Variable Set [ Name:%path To:/api/services/script/turn_on Recurse Variables:Off Do Maths:Off Append:Off ] 
A3: Variable Set [ Name:%entityname To:script.scriptname Recurse Variables:Off Do Maths:Off Append:Off ] 
A4: Variable Set [ Name:%token To:Bearer ABCDEFGHIJK Recurse Variables:Off Do Maths:Off Append:Off ] 
A5: JavaScriptlet [ Code:var uri = url+path;
var data = {entity_id: entityname};
var xhttp = new XMLHttpRequest(); 
xhttp.open( "POST", uri, false ); 
xhttp.setRequestHeader('Authorization', token); 
xhttp.setRequestHeader('Content-Type', 'application/json'); 
xhttp.send(JSON.stringify(data)); 
var rtresponse = xhttp.response; 
var rtcode = xhttp.status; 
Libraries: Auto Exit:On Timeout (Seconds):10 ] 

Although this could be written as a single JavaScriptlet action, I broke out the IP, service path, entityname and Access Token into local variable descriptions to make any maintenance slightly easier.

2 Likes

Good work, would you mind add your solution to our cookbook?

I’ve taken a look at the cookbook.

I’m assuming I’d need to add a new section and then upload a suitably redacted example, presumably exported as XML and appropriately commented?
Apologies if this is more obvious than I think - I’m a little bit fried at the moment after migrating to new firewalls at work and mopping up the resulting collateral damage, so I may not be reading things terribly clearly

If you could give a little guidance then I’ll have a crack at it over the weekend.

You can start from clone https://github.com/home-assistant/home-assistant.io/blob/current/source/_cookbook/owntracks_two_mqtt_broker.markdown file, put it in the same folder (of course you need first fork and create your branch).

I think as long as you preserve following block in the facade area, this file will be auto-indexed to cookbook page.

ha_category: Infrastructure

Thanks for offering some guidance, but I’m not familiar with using GitHub and don’t really have the bandwidth to learn another source code control system at the moment. I was (perhaps naively) expecting the process of submitting an example to be a little simpler, but I do understand the reasoning behind it.

I have mocked up a valid RestAPICallExample.tsk.xml attached below with the description export blockquoted in case it is of use: .

RestAPICallExample.tsk.xml (1.6 KB)

RestAPICallExample (3)
A1: Variable Set [ Name:%url To:http://IPADDRESS:8123 Recurse Variables:Off Do Maths:Off Append:Off ]
A2: Variable Set [ Name:%path To:/api/services/script/turn_on Recurse Variables:Off Do Maths:Off Append:Off ]
A3: Variable Set [ Name:%entityname To:script.name_of_script Recurse Variables:Off Do Maths:Off Append:Off ]
A4: Variable Set [ Name:%token To:Bearer ABCDEFGHIJKLMNO Recurse Variables:Off Do Maths:Off Append:Off ]
A5: JavaScriptlet [ Code:var uri = url+path;
var data = {entity_id: entityname};
var xhttp = new XMLHttpRequest();
xhttp.open( “POST”, uri, false );
xhttp.setRequestHeader(‘Authorization’, token); xhttp.setRequestHeader(‘Content-Type’, ‘application/json’); xhttp.send(JSON.stringify(data));
var rtresponse = xhttp.response;
var rtcode = xhttp.status; Libraries: Auto Exit:On Timeout (Seconds):10 ]

6 Likes

I tried your task (with my url and entityname) and I received a response code 401. The same token works with HA Client.

@TazUk
Thanks for this info and the example! :+1: I’m all for performing actions natively with Tasker whenever possible (more moving parts always complicates things). I imported your example, tweaked the variables for use in my setup and it works perfectly!

Thanks again for taking the time to post this! :smile:

2 Likes

Bieniu:
Status code 401 indicates unauthorized, indicating an issue with the %token variable in your version.
Did you retain the "Bearer " prefix?

Yes “Bearer” prefix was a solution. Thanks.

well done! but howto update a sensor with that command?

In the past i tracked my battery level with a json payload like

{"state":"%BATT", "attributes": {"friendly_name": "cellular batt", "icon":"mdi:cellphone","unit_of_measurement":"%"}}

My example calls a script that sets a boolean, triggering an automation.
The developer docs https://developers.home-assistant.io/docs/en/external_api_rest.html cover passing JSON data as a parameter.

You should be able to modify my example accordingly. I’m still in the process of building out the infrastructure and will not get to additional RestAPI use until the subscription Cloud connection comes online