Session Authentication in NSX and the Bad XSRF Token

Well, it's been a while since I posted here, but this one was a real head scratcher with ultimately a simple solution, so I figure that I should put it out there!  I've been working with the NSX API lately and wanted to do session based authentication rather than throwing credentials at the system for every operation.  I followed the official guide (as best I could, given that I'm working in PowerShell), so then I followed some really helpful blog posts, and it looked like I had everything right... but I was getting this Bad XSRF Token error that I didn't understand.

I did a bunch of fruitless research before I noticed something.  My $headers variable had the XSRF token enclosed in curly brackets, as it came from the value of a hashtable (as seen in Lorenzo's script here):

$xsrftoken = $response.headers["X-XSRF-TOKEN"]
...
$script:headers.Add("X-XSRF-TOKEN", $xsrftoken)

That didn't look right to me.  I was grasping at straws, so I tried populating my $headers hashtable with the copy-pasted values from that response, which was basically all of the characters without the enclosing curly brackets... and it worked like a champ!  I'm not sure why PowerShell was baking those curly brackets into the string, but it was messing everything up.  My solution to it was a little piece of duct tape:

$script:headers.Add("X-XSRF-TOKEN", "$($response.headers["X-XSRF-TOKEN"])")

Given that the hashtable was already returning a string without curly brackets for the value of the X-XSRF-TOKEN entry, I'm not sure why the original method was populating with them... but throwing that value into a string when adding it to my $headers variable got everything working!


Comments

Popular posts from this blog

Clone a Standard vSwitch from one ESXi Host to Another

Orphaned VMDK Files

ESXi Syslog to Multiple Servers