Search code examples
powershellinvoke-command

Invoke-WebRequest Leaving Sessions Open


Ive written a script to login to a customers website. Everything works just fine, but they reported back to be that they are seeing stale sessions from the account that I use. I am at a loss for how to fix this as my googlefu is returning nothing. Here is the code I wrote:

$c = Get-Credential -credential ${CREDENTIAL}

$loginbase = 'http://${IP}'
$loginURL = $loginbase + '/AdminTools/querybuilder/'
$r = Invoke-WebRequest -Uri ($loginURL + 'logonform.jsp') -SessionVariable session

$form = $r.Forms[0];

$form.Fields['aps'] = '${Node.DNS}:6400';
$form.Fields['usr'] = $c.Username;
$form.Fields['pwd'] = SecureStringToString $c.Password;

$r = Invoke-WebRequest -Uri ($loginURL + $form.Action) -Method POST -Body $form.Fields -WebSession $session;

Ive been staring at this for far too long and just need another set of eyes to nudge me in the correct direction.

In the event it does matter, I have run this script with and without a sessionvariable. My initial though was that the session was causing the session to stay open and would be reused when it attempts to login again. Also, this is part of a monitoring solution, so it is set to attempt to login every 120 seconds.


Solution

  • As the session is being maintained by something on the web server, your script needs to take a "log out" action to allow the web server to close out your session. The maintainer of that website should have a URL you can invoke a request to which will perform that log out action and clean up any resources on their server.