Saturday, May 22, 2021

Tip: How-To get non-persistent cookie (e.g ASP.NET_SessionId) within PowerShell

Context of my need: a COTS application deployed as Azure WebApp that is also used as REST Api by this webapplication, and the need to automate some of the provision capabilities in this application. The user-based authentication and access control on the Azure WebApp as Api is implemented by leveraging the SharePoint Add-In model, with the remote Azure App launched via AppRedirect.aspx. And next the Api endpoints check the 'SPAppToken' cookie included in Api request, plus the "ASP.NET_SessionId".
The first is rather simple to get hands on in PowerShell code, by 'Invoke_WebRequest' to AppRedirect.aspx with the proper launch parameters; and from the WebResponse object parse the SPAppToken value that is returned in body of the response.
However, the 2nd is more tricky: it is returned as non-persistent cookie in the response, and default not available within PowerShell automation context to read from the WebResponse object. I tried the approach described in Cannot get authentication cookie from web server with Invoke-WebRequest. Without success, but it did inspire me to an alternative approach; and that does work:

  function GetAzureAppASPNetSessionId() {
     $appLaunchCookies = "SPAppToken=$global:AzureSPAppToken&SPSiteUrl=$([System.Web.HttpUtility]::UrlEncode($global:targetSite))"
     $url = "$azureAppLaunchUrl/?SPHostUrl=$([System.Web.HttpUtility]::UrlEncode($global:targetSite))";

     $WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession;
     $wr1 = Invoke-WebRequest -Uri $url -Method Post -Body $akuminaCookie -WebSession $WebSession;

     $cookieCont = $WebSession.Cookies.GetCookies($appLaunchCookies);
     $aspNetSessionIdCookie =  $cookieCont | Where {$_.Name -eq "ASP.NET_SessionId" };
     if ($aspNetSessionIdCookie) {
        return $aspNetSessionIdCookie.Value;
    }
}

No comments:

Post a Comment