Use PowerShell Invoke-WebRequest to login on a website

To automate some tasks with PowerShell on a website you sometimes need to log in. Today I tried some curl and postman tricks but it isn’t hard if you know what to script with PowerShell and bypass all other tools.

First, find a website to log in to, then check the page source and what the submit button does. In this example, it is “Inloggen” (dutch for login).

Then start the developer tools (F12), select the network tab, enter the credentials and login.

Now check the POST request in the developer tools.

The important things on this login form are:

  • Gebruikersnaam (username)
  • Wachtwoord (password)
  • __RequestVerificationToken

Now we can write a simple script

$LoginUri = "https://example.website.nl/versie6-0-0/mijnscore/Login"
$BackendUri = "https://example.website.nl/mijnzwemscore/inhaalles.asp"
# ==========================================
$LoginResponse = Invoke-WebRequest -Uri $LoginUri -SessionVariable "Session" 
$LoginBody = @{
    __RequestVerificationToken = $LoginResponse.InputFields[1].value
    Gebruikersnaam             = "EnterUsername"
    Wachtwoord                 = "EnterPassword"
    Submit                     = "Inloggen"
}
$LoginResponse = Invoke-WebRequest -Uri $LoginUri -WebSession $Session -Body $LoginBody -Method "POST"

Invoke-WebRequest -Uri $BackendUri -WebSession $Session 

Explanation of the script:

  1. Open the website and find out what the __RequestVerificationToken must be
  2. Create a body with the credentials, the login form submit and the __RequestVerificationToken
  3. Do the actual login and save the web session (cookies and stuff).
  4. Now we can use the previous web session to check all the backend stuff

Happy Scripting 🙂

Author: Thomas Faddegon

Do you like my posts and want to do something back? You can buy me a beer :)