Hi everyone,
Given the following simplified authentication handler for /api/login
in a UDRestApi
:
$LoginAuth = New-UDAuthenticationMethod -Endpoint {
Param([PSCredential]$Credential)
try {
$account = Get-ADUser $Credential.UserName -Credential $Credential
} catch {
New-UDAuthenticationResult -ErrorMessage "Invalid credentials"
}
New-UDAuthenticationResult -Success -UserName $account.SamAccountName -Role Admin
}
The result of an authentication failure is always a 500 errror. Not the expected JSON payload with success: false
and errorMessage
. But if the authentication is successful (i.e. if Get-ADUser
does not throw an exception) authentication will succeed.
Trying to simplify this even more, I cannot reproduce throwing a simple exception like this:
try {
throw "TEST"
} catch {
New-UDAuthenticationResult -ErrorMessage "Invalid credentials"
}
Using this authentication code, I will always get a proper JSON response, not a 500 error.
I figured out that a 500 error code seem to be returned if a terminating ErrorRecord is created, for example like this:
try {
Write-Error "BOOM" -ErrorAction Stop
} catch {
New-UDAuthenticationResult -ErrorMessage "Invalid credentials"
}
And if instead we have a non-terminating ErrorRecord created during the execution like this:
Write-Error "BOOM"
New-UDAuthenticationResult -ErrorMessage "Invalid credentials"
The resulting API response will be 200 with a body of:
{
"error": "BOOM"
}
I am not sure what to make of this. I have yet to test if this applies to all endpoints or if this is specific of the authentication method, but it is causing me quite a headache already.
I need to authenticate users against ADand get their roles from AD as weel before I give them a token for the REST API access. I need to be able to handle errors without the API framework taking over like the boss of me and assuming the worst. If this applies to all endpoints as well, there better be a workaround otherwise it will effectively make my project a no go.
Any way to work around this? Did I miss something important in the documentation?
Thanks!
Marco