node-unifi
node-unifi copied to clipboard
CSRF token not always set
Thanks for this package. I've been using v1.x for more than a year and it's been working very stable. But with the most recent UnifiOS and Network application update, my simple LED updater stopped working, so I went on to update node-unifi to v2.
But I hit a bit of an issue. This one actually took me a few hours to understand (though I have not yet been able to figure out a solution, only a workaround), and it seems to be related to #157.
I am doing the following:
const unifi = new Controller({ host, port, username, password, sslverify: false });
await unifi.login();
await unifi.setLEDOverride(id as string, value ? 'on' : 'off');
But I get a 403 error with "Invalid CSRF Token" because no token is set.
It seems login does not set a token, and if I do not have another request of some kind before doing the LED override, then it will fail due to the token not being set.
As a workaround I have the following line before setLEDOverride:
// This is a workaround to make sure the CRSF token is updated
await unifi.getAccessDevices(mac);
This will get data for the device, that I don't need, but it will also update the CSRF token from the response.
I guess login should take care of this or _init should but neither seem to do that. Or maybe _request can check for it and pull it if not available.
Workaround works well for now and I'm just doing one extra request, but if you have happen to get a fix done, then I am ready to test that :)
I think this could affect many other commands if used without pulling device data before.
Which version of node-unifi do you use? In 2.0.5 I already fixed CSRF related issues with latest unifios devices. Thus, the latest 2.1.0 should not have that issue!
Sorry, I tested both 2.1.0 and 2.0.5 and both have the issue.
On 2.1.0, unifios csrf token still does not work, Invalid token error response 403.
Quite a few clients rely on this so please fix :)
Hello, I want to bump this by saying that the Invalid X-CSRF Token error is still appearing on CKG2+ and UDM SE. Is there any fixes available?
Found the issue: at the end of async login function:
let response = await this._instance.post(endpointUrl, {
username: this.opts.username,
password: this.opts.password
});
if (response.headers['x-csrf-token']) {
this._xcsrftoken = response.headers['x-csrf-token'];
this._instance.defaults.headers.common['x-csrf-token'] = this._xcsrftoken;
}
return true;
@vishal1503 Then please provide a PullRequest if possible so that this can be analyzed and integrated.
fixed by #199
I can confirm this fixed my issue! I no longer need to do another API call before the LED update for it to work.
Thanks, everyone!