Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue on verifying user login name and password

Tags:

c#

.net-4.0

Friends I need to make a software that needs to verifies the valid user login in order to use software. I tried this:

bool valid = false;
 using (PrincipalContext context = new PrincipalContext(ContextType.Domain,domainname))
 {
     valid = context.ValidateCredentials( username, password );
 }

I am using .net framework 4 . In this above code how to get domainname of the computer. I have tried SystemInformation.ComputerName ,SystemInformation.UserDomainName but i got error as :

The server could not be contacted

. And Can we get the current username and password using any header file in c# ?? Please answer. Edits: I am using this for local login in my computer or AD.

like image 219
progrrammer Avatar asked Feb 21 '23 18:02

progrrammer


1 Answers

There's no way to get the user's password. That could lead to all sorts of security issues. And if you want to verify credentials beyond what the machine already knows from the Windows logon you need to ask the user for the password anyway.

The following code works for me in a forest with many domains. If you don't specify a domain in the PrincipalContext constructor it connects to the domain of the computer it's running on. In my testing it doesn't matter if the user you're validating is in a different domain, as long as appropriate trusts exist between the domains in the forest.

bool valid = false;
using (var context = new PrincipalContext(ContextType.Domain))
{
    valid = context.ValidateCredentials(username, password);
}

You can get an object representing the current user like this:

var user = System.Security.Principal.WindowsIdentity.GetCurrent();

Update

If you're wanting to check credentials against the local account database on the machine then just change the type of the PrincipalContext:

bool valid = false;
using (var context = new PrincipalContext(ContextType.Machine))
{
    valid = context.ValidateCredentials(username, password);
}
like image 153
Andrew Cooper Avatar answered Mar 05 '23 13:03

Andrew Cooper