TrueNAS 12 BETA using API keys with the REST API 2.0

datamattsson

Cadet
Joined
Jul 21, 2020
Messages
8
I'm working on a custom integration that leverages the REST API 2.0 on TrueNAS 12 BETA. Works great using basic authentication with the root account. However, I can see that there are API keys you can generate and I'm wondering how to use these keys instead. I can't find any documentation anywhere on this subject.
 

waqarahmed

iXsystems
iXsystems
Joined
Aug 28, 2019
Messages
136
Hi @datamattsson. The steps for that are to first create an api key, once you have an api key, we just use it as a bearer token. I add the following to my headers while making a request
{
'Content-Type': 'application/json',
'Authorization': 'Bearer 1-Pe9VwiV5B70yrq8kM8RmtkhDP4dAnFw5VSsFtSfq47WzfpxwYdb8fUKalAWIWtr0'
}

And it works as desired. Please let me know if you run into any issues. Thank you
 
Joined
Dec 28, 2020
Messages
18
Hey! I've been having issues with this when using requests in python. I might just be mucking up my headers. Any advice?
Here's an example below, where I can query my list of rsync modules using the root password, but not when using my API key.
~> ipython
Python 3.9.5 (default, May 18 2021, 12:31:01)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.3.0 -- An enhanced Interactive Python. Type '?' for help.

[ins] In [1]: import requests

[ins] In [2]: api_key = open('.config/truenas/my_api_key.txt', 'r').read().strip()

[ins] In [3]: root_password = open('root_password.txt', 'r').read().strip()

[ins] In [4]: auth_dict = {"Content-Type": "application/json; charset=utf-8", "Authorization": f"Bearer {api_key}"}

[ins] In [5]: r = requests.get("http://192.168.1.2/api/v2.0/rsyncmod", headers=auth_dict)

[ins] In [6]: r
Out[6]: <Response [401]>

[ins] In [7]: r = requests.get("http://192.168.1.2/api/v2.0/rsyncmod", auth=("root", root_password))

[ins] In [8]: r
Out[8]: <Response [200]>
 
Joined
Dec 28, 2020
Messages
18
Thanks for the tip! Sadly, no luck:


Code:
 ~> ipython
Python 3.9.5 (default, May 18 2021, 12:31:01)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.3.0 -- An enhanced Interactive Python. Type '?' for help.

[ins] In [1]: import requests

[ins] In [2]: api_key = open('.config/truenas/pml_key.txt', 'r').read().strip()

[ins] In [3]: auth_dict = {"Authorization": f"Bearer {api_key}"}

[ins] In [4]: r = requests.get("http://192.168.1.2/api/v2.0/rsyncmod", headers=auth_dict)

[ins] In [5]: r
Out[5]: <Response [401]>

[ins] In [6]: r.text
Out[6]: '401: Unauthorized'
 
Joined
Dec 28, 2020
Messages
18
Success! I made a new API key. The starting "1-" in the key should have been a tell. The new one has "2-" as a prefix and works fine.
 

danb35

Hall of Famer
Joined
Aug 16, 2011
Messages
15,504
Top