API token instead of username:password in python requests.put script

I have a python script running and that sends values off to the REST-API. This works great but the username and (even worse) password are in the script in plain text.

my_headers = {'accept': ' */*', 'Content-Type': 'text/plain'}
url = 'http://*OH-IP*:8080/rest/items/ring_batterij/state'
response = requests.put(url, headers=my_headers, auth=HTTPDigestAuth('*****','*****'), data=str(bat))

I have tried using the token. It generated OK but I have trouble implementing it. I found this script: my_headers = {'Authorization' : 'Bearer {access_token}'} and tried to add that to the ‘my_header’ but it comes back as a 401 error (access denied).

Anyone who got this working?

Which authentication schema do you want to use ? Basic Authentication using a token or OAUTH2 using a token ?
According to your post’s content it looks like it would be OAUTH2 ? Then you create a token like described here: [OH3] REST API Authentication Help RESOLVED ?

In case you would like to use Basic Authentication using a token your header is wrong. Look here: Using the API Token with python - #16 by ysc

Both threads give a bit more background information.

You wrote

is that different using tokens in the script ?

@Spaceman_Spiff has implemented that in Python3 with HABApp. Perhaps take a look at how he did things.

Thank you both for the replies.

Yes, the token can’t be used to log into the main ui. Also, I have a password that I can remember and that token is for sure out of my league to remember!

I have seen this passing by a couple of times. I will take a look. Also in the threats @Wolfgang_S mentioned.

Hopefully you mean threads, not threats LOL Here is the Python source

Oops :kissing_smiling_eyes:

1 Like

I’m using an ECMA script rule like that:

var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
var HTTP=Java.type("org.openhab.core.model.script.actions.HTTP");
var openHAB_PID =Exec.executeCommandLine(parseDuration("1s"), "pgrep", "-f", "openhab.*java");
headers["Authorization"] = "Bearer oh.RESTCall.xyz";
headers["WWW-Authenticate"] =  "Basic";
systemstatus_thing=HTTP.sendHttpGetRequest("",headers, 10000);
systemstatus_thing=systemstatus_thing.replaceAll('"pid":([0-9]+)','"pid":' + openHAB_PID);
var returnvalue = HTTP.sendHttpPutRequest("", "application/json", systemstatus_thing,headers, 10*1000);

Thanks all for the help! I now managed to get it working :facepunch:t2:

1 Like