Generate NSX ALB CSRFToken in Orchestrator

Learn how to generate a CSRFToken for NSX ALB (formerly Avi Networks) while working with REST APIs in Orchestrator.

By

min read

Generate NSX ALB CSRFToken in Orchestrator

To get the value from cookie in orchestrator was a little new to me. I have never done this earlier or even seen any example.

I got a requirement to get create automation workflow for deleting Service Engine Groups in VMware NSX ALB (formerly Avi Networks) and for that I was using REST API instead of the Avi Controller plugin for vRO which felt half-baked to me and I couldn’t use it properly for my use case.

The first requirement for using ALB REST API is to pass a CSRFToken in each subsequent POST/PUT/DELETE call after you login using your credentials.

I did the API trial on Postman and started wokring on creating an action but I just couldn’t figure out how this CSRFToken is being generated and shown in the Cookies section in Postman. I started wondering how would I replicate this in Orchestrator.

After spending a good time, I got my answer. We can simply get the values in cookies by accessing them from the REST Transient host object as seen in this below script.

var restHost = RESTHostManager.createHost("DynamicRequest");
restHost.url = "https://alb_fqdn";
var transientHost = RESTHostManager.createTransientHostFrom(restHost)
var credentials =  {'username': 'user1',
    'password': 'pa$$w0rd!'};
var stringifiedCredentials = JSON.stringify(credentials);
var request = transientHost.createRequest("POST", "/login", stringifiedCredentials); 
request.contentType = "application/json";

var response = request.execute();
System.log("getNsxAlbToken action response code: " + response.statusCode);
if(response.statusCode == 200){
    for each (var i in transientHost.cookies){
        if(i.name == "csrftoken") return i.value;
    }
} else throw "getNsxAlbToken action response code is not 200. Check credentials or url. Cannot Proceed!";
JavaScript

It was a nice quick trick unless you know it. Hence, I have shared it here for everyone else. I hope you like it. Thanks for reading.

Link to AVi REST API Guide is here.

Leave a Reply

Related Posts

%d bloggers like this: