Forms

Basic forms authentication

Download this Lecture Docs

In this lecture, we'll look at how to configure forms authentication. First, I'll talk about how to securely store credentials and check them within the forms authentication script. Next, we'll look at how to assign custom claims to a user during login. Finally, we'll map a built-in PSU role to the custom claim.

Example Code used in this Lecture

Compare-SecureString


param(
    [PSCredential]$Credential
  )

    function Compare-SecureString {
    param(
      [Security.SecureString] $secureString1,
      [Security.SecureString] $secureString2
    )
    try {
      $bstr1 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString1)
      $bstr2 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString2)
      $length1 = [Runtime.InteropServices.Marshal]::ReadInt32($bstr1, -4)
      $length2 = [Runtime.InteropServices.Marshal]::ReadInt32($bstr2, -4)
      if ( $length1 -ne $length2 ) {
        return $false
      }
      for ( $i = 0; $i -lt $length1; ++$i ) {
        $b1 = [Runtime.InteropServices.Marshal]::ReadByte($bstr1, $i)
        $b2 = [Runtime.InteropServices.Marshal]::ReadByte($bstr2, $i)
        if ( $b1 -ne $b2 ) {
          return $false
        }
      }
      return $true
    }
    finally {
      if ( $bstr1 -ne [IntPtr]::Zero ) {
        [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr1)
      }
      if ( $bstr2 -ne [IntPtr]::Zero ) {
        [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr2)
      }
    }
  }
  
  if ($Credential.UserName -eq $AdminAccount.UserName -and (Compare-SecureString -secureString1 $Credential.Password -secureString2 $AdminAccount.Password)) {
    New-PSUAuthenticationResult -Success -UserName 'Admin' -Claims { 
      New-PSUAuthorizationClaim -Type 'Role' -Value 'MyRole'
     }
  }
  else {
    New-PSUAuthenticationResult -ErrorMessage 'Bad username or password'
  }