Reputation: 25308
I am just now exploring the API Test capabilities in Fiddler. What a boon! I have this question:
When running a sequence of calls, the first call is to LOGIN. The result of this call contains an Access Token. On all subsequent calls, the HEADER needs to have this token in the form of:
Authorization: Bearer eyJ0eXAiOiJKV1QiLC......
How do I script this so that the following tests have the new token assigned?
Upvotes: 0
Views: 2056
Reputation: 25308
Puzzled it out:
static function BeforeTestList(arrSess: Session[]): boolean
{
// In this method, you can do any setup you need for the test,
// e.g. adding an Authorization: token OAUTH value that you
// obtained programmatically...
var sOAUTHToken = obtainToken();
if (String.IsNullOrEmpty(sOAUTHToken)) return false;
for (var i: int=0; i<arrSess.Length; i++)
{
arrSess[i].oRequest["Authorization"] = sOAUTHToken;
}
MessageBox.Show("Token Set. Running " + arrSess.Length.ToString() + " tests.", "BeforeTestList");
return true; // Test should proceed; return false to cancel
}
static function obtainToken()
{
try
{
var Content: byte[] = System.Text.Encoding.UTF8.GetBytes("{\"UserName\":\"username\",\"Password\":\"password\"}");
var oRQH: HTTPRequestHeaders = new HTTPRequestHeaders("/auth/login", ['Host: localhost:58960','Content-Length: ' + Content.length.ToString(), 'Content-Type: application/json']);
oRQH.HTTPMethod = "POST";
var oSD = new System.Collections.Specialized.StringDictionary();
var newSession = FiddlerApplication.oProxy.SendRequestAndWait(oRQH, Content, oSD, null);
if(newSession.responseCode == 200)
{
var bodyStr = newSession.GetResponseBodyAsString();
var bodyJson=Fiddler.WebFormats.JSON.JsonDecode(bodyStr);
var token = bodyJson.JSONObject["accessToken"];
//MessageBox.Show("Authorization: Bearer " + token);
return "Bearer " + token;
}
}
catch(e)
{
MessageBox.Show("send failed" + e.ToString());
}
}
Upvotes: 1