Ad Widget

Collapse

Bearer token automatic retrival

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • danielec
    Junior Member
    • Oct 2025
    • 5

    #1

    Bearer token automatic retrival

    Hi there,
    I want to query an external API that requires authentication via Bearer token. This token is short lived (a few hours) and need to be refreshed automatically. This is useful for REST APIs.
    I've read many suggestions but I wanted it to be running without external scripts so I wrote a little Javascript that fetches the token and saves it in a user macro, to be used in the actual Item that fetches the external API I want to monitor. The script needs a Zabbix API Token to be able to update the user macro.

    Code:
    try {
        req = new HttpRequest();
        req.addHeader('Content-Type: application/json');
        req.addHeader('Accept: application/json');
    
        resp = req.post('<URL to fecth the token>', JSON.stringify({
        'accessKey': 'xxxxxxxx',    <-- You should edit these as required
        'secretKey': 'xxxxxxxx'
        }));
    
        if (req.getStatus() != 200) {
            throw 'Response code: '+req.getStatus();
        }
        
        resp = JSON.parse(resp);
        bearer = resp.access;
        
        upd = new HttpRequest();
        upd.addHeader('Content-Type: application/json-rpc');
        upd.addHeader('Authorization: Bearer <Zabbix API Token>');
    
        result = upd.post('https://<zabbix URL>/api_jsonrpc.php',JSON.stringify( {
       "jsonrpc": "2.0",
       "method": "host.update",
       "params": {
           "hostid": "12345",    <-- This is the host for whitch the macro needs to be set. Be careful as this will delete other user macro for the same host.
           "macros": [
               {
                   "macro": "{\$BEARER}",  <-- User macro name
                   "value": bearer,
                   "description": "Automatically updated - do not edit"
               }
           ]
       },
       "id": 1
    }));
        return result;
        
      } catch (error) {
        throw error;
      }
    Basically I have one host with two Items. One item is "getBearer", type "Script" with the JS code above, that runs every 2 hours (or what's needed to keep the bearer fresh).
    The other Item is the item I actually want to retrieve, type "HTTP agent" that uses the {$BEARER} user macro when needed.

    Hope this helps.
    dan
Working...