OPNsense Forum

English Forums => General Discussion => Topic started by: D0doooh on March 25, 2023, 12:30:41 PM

Title: [Solved] Unable to add IP addresses to an alias using API
Post by: D0doooh on March 25, 2023, 12:30:41 PM
I am currently facing some issues adding an IP address to an alias using the API. I have followed the documentation and tried calling the corresponding endpoint, but it doesn't seem to be working.

here is my code:


function urlEncodeFormData(data) {
    return Object.keys(data)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
        .join('&');
}

let extractedIPs = [];

for (let key in msg.payload) {
    if (msg.payload.hasOwnProperty(key)) {
        extractedIPs.push(msg.payload[key].ipAddress);
    }
}

let opnsenseUrl = 'https://OPNSENSE';

msg.url = opnsenseUrl + '/api/firewall/alias/addItem';

msg.method = 'POST';

const payloadData = {
    enabled: 1,
    name: "AuthUsers",
    type: "host",
    proto: "IPv4",
    content: extractedIPs.join(","),
    description: "Auth users IP addresses"
};

msg.payload = urlEncodeFormData(payloadData);

const apiKey = 'API_KEY';
const apiSecret = 'API_SECRET';

const auth = 'Basic ' + Buffer.from(apiKey + ':' + apiSecret).toString('base64');

msg.headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': auth
};

return msg;



this is the json i am submitting:

{"User01":{"ipAddress":"1.1.1.1","timestamp":"2023-03-25T02:52:50.447Z"},"User02":{"ipAddress":"2.2.2.2","timestamp":"2023-03-25T02:52:43.386Z"}}

the api otherwise works, I can make queries, I think I understand only something small wrong or is not formatted correctly.

the post request looks like this:

enabled=1&name=AuthUsers&type=host&proto=IPv4&content=1.1.1.1%2C2.2.2.2&description=Auth%20users%20IP%20addresses

Thanks a lot!
Title: Re: Unable to add IP addresses to an alias using API
Post by: D0doooh on March 27, 2023, 01:10:29 AM
so after a little try and error, I got it to run, the problem was the URL, this must have the alias in the URL:

var payload = {
"address": msg.payload
};
var url = https://OPNSESNE.lan/api/firewall/alias_util/add/AuthUsers;
msg.url = url; msg.method = "POST"; msg.headers = { "Content-Type": "application/json" }; msg.payload = JSON.stringify(payload);
return msg;