Test user credentials

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 7 years and 3 weeks old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
AG_G1_
Posts: 6
Last visit: Sun Mar 05, 2017 10:51 am

Test user credentials

Post by AG_G1_ »

Hello,

The code below is my function to test user credentials wherever I'm in a domain or not, disconnected from the network or not. It's working great, thanks to Andy Arismendi. But I have an issue if there is a mapped drive connected with my credentials. The function will always return $true.

Can someone help me please?
  1. function Test-UserCredential{
  2.         [CmdletBinding(DefaultParameterSetName = "PSCredential")]
  3.         [OutputType("set1", [System.Boolean])]
  4.         [OutputType("PSCredential", [System.Boolean])]
  5.         param(
  6.                 [Parameter(Mandatory=$true, ParameterSetName="set1", position=0)]
  7.                 [ValidateNotNullOrEmpty()]
  8.                 [String] $Username,
  9.  
  10.                 [Parameter(Mandatory=$true, ParameterSetName="set1", position=1)]
  11.                 [ValidateNotNullOrEmpty()]
  12.                 [System.Security.SecureString] $Password,
  13.  
  14.                 [Parameter(Mandatory=$true, ParameterSetName="PSCredential", ValueFromPipeline=$true, position=0)]
  15.                 [ValidateNotNullOrEmpty()]
  16.                 [Management.Automation.PSCredential] $Credential,
  17.  
  18.                 [Parameter(position=2)]
  19.                 [Switch] $Domain,
  20.  
  21.                 [Parameter(position=3)]
  22.                 [Switch] $UseKerberos
  23.         )
  24.  
  25.         Begin {
  26.                 try { $assem = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement') }
  27.                 catch { throw 'Failed to load assembly "System.DirectoryServices.AccountManagement". The error was: "{0}".' -f $_ }
  28.  
  29.                 $system = Get-WmiObject -Class Win32_ComputerSystem
  30.  
  31.                 if (0, 2 -contains $system.DomainRole -and $Domain) {
  32.                         throw 'This computer is not a member of a domain.'
  33.                 }
  34.         }
  35.  
  36.         Process {
  37.                 try {
  38.                         switch ($PSCmdlet.ParameterSetName) {
  39.                                 'PSCredential' {
  40.                                         if ($Domain) {
  41.                                                 $Username = $Credential.UserName.TrimStart('\')
  42.                                         } else {
  43.                                                 $Username = $Credential.GetNetworkCredential().UserName
  44.                                         }
  45.                                         $PasswordText = $Credential.GetNetworkCredential().Password
  46.                                 }
  47.                                 'set1' {
  48.                                         $PasswordText = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
  49.                                                         [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
  50.                                 }
  51.                         }
  52.  
  53.                         if ($Domain) {
  54.                                 $pc = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
  55.                         } else {
  56.                                 $pc = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
  57.                         }
  58.  
  59.                         if ($Domain -and $UseKerberos) {
  60.                                 return $pc.ValidateCredentials($Username, $PasswordText)
  61.                         } else {
  62.                                 return $pc.ValidateCredentials($Username, $PasswordText, [DirectoryServices.AccountManagement.ContextOptions]::Negotiate)
  63.                         }
  64.                 } catch {
  65.                         throw 'Failed to test user credentials. The error was: "{0}".' -f $_
  66.                 } finally {
  67.  
  68.                 }
  69.         }
  70. }
To test credentials, I type this:
  1. $MyPassword = $TextBox.Text | ConvertTo-SecureString -AsPlainText -Force
  2. Test-UserCredential -user $MyUser -password $MyPassword
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Test user credentials

Post by jvierra »

Yes. This is not a reliable way to test credentials.

What is the purpose of testing credentials?
User avatar
AG_G1_
Posts: 6
Last visit: Sun Mar 05, 2017 10:51 am

Re: Test user credentials

Post by AG_G1_ »

It's for making scheduled tasks via a form where there are among other things two textbox (
  1. ([Security.Principal.WindowsIdentity]::GetCurrent()).Name
& password) and a buton to check credentials. If those are goods, I can register some scheduled tasks by simple click.

I tried several ways but I didn't find one working wherever I'm in a domain or not and if I'm offline or not (exemple: I'm connected with domain user but I'm offline).
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Test user credentials

Post by jvierra »

If the credentials are bad the registration of the task will fail. The scheduler API tests the creds when you register the task.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Test user credentials

Post by jvierra »

Here is what happens when you use invalid credentials:
  1. D:\scripts> $task | Register-ScheduledTask -TaskName TestCreds -User TestUser -Password Pass@Word^%
  2. Register-ScheduledTask : The user name or password is incorrect.
  3. At line:1 char:9
  4. + $task | Register-ScheduledTask -TaskName TestCreds -User TestUser -Pa ...
  5. +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  6.     + CategoryInfo          : AuthenticationError: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-Sche
  7.    duledTask], CimException
  8.     + FullyQualifiedErrorId : HRESULT 0x8007052e,Register-ScheduledTask
User avatar
AG_G1_
Posts: 6
Last visit: Sun Mar 05, 2017 10:51 am

Re: Test user credentials

Post by AG_G1_ »

Indeed. So how can I catch a failed registration whatever the authentication error. I'd like to avoid getting an unreadable message for the user who will use my form?
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Test user credentials

Post by jvierra »

Use Try/Catch and check the error.
User avatar
AG_G1_
Posts: 6
Last visit: Sun Mar 05, 2017 10:51 am

Re: Test user credentials

Post by AG_G1_ »

Well, I tried a try/catch but I didn't succeed.
If the password is empty, it's freezing. And if the password is wrong, the message saying that the user or password is wrong is written in the console and the finally block shows up.
  1. $handler_SetTaskButton_Click=
  2. {
  3.  
  4. try {
  5. schtasks.exe /Create...
  6. }
  7. Catch {
  8. [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
  9.  [output][System.Windows.Forms.MessageBox]::Show("$LASTEXITCODE")[/output]
  10. }
  11. Finally{
  12. [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
  13.  [output][System.Windows.Forms.MessageBox]::Show("Worked fine.")[/output]
  14. }
  15.  
  16. }
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Test user credentials

Post by jvierra »

Use Register-0ScheduledTask. SchTasks will not work as you want.

Try/Catch does not catch errors in external programs. We use $LASTEXITCODE for that,
User avatar
AG_G1_
Posts: 6
Last visit: Sun Mar 05, 2017 10:51 am

Re: Test user credentials

Post by AG_G1_ »

Well, a lot of my clients still use W2008 (6.0), so I can't update to Powershell 4...
This topic is 7 years and 3 weeks old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked