- 1 year ago
Validate Local Windows Account Username and Password in .NET Core 3.1
To validate a local Windows account username and password in .NET Core 3.1, you can use the System.DirectoryServices.AccountManagement
namespace, which provides classes for working with directory services, including validating user credentials. Here's an example:
csharpusing System;
using System.DirectoryServices.AccountManagement;
public class AccountValidator
{
public static bool ValidateCredentials(string username, string password)
{
try
{
using (var context = new PrincipalContext(ContextType.Machine))
{
return context.ValidateCredentials(username, password);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred during credential validation: " + ex.Message);
return false;
}
}
}
In the ValidateCredentials
method, you create a PrincipalContext
object with the ContextType.Machine
option to establish a context for validating credentials against the local machine. Then, you use the ValidateCredentials
method of the PrincipalContext
object to check if the provided username and password are valid.
To use the ValidateCredentials
method, you can call it with the username and password you want to validate:
csharpstring username = "myuser";
string password = "mypassword";
bool isValid = AccountValidator.ValidateCredentials(username, password);
if (isValid)
{
Console.WriteLine("Credentials are valid.");
}
else
{
Console.WriteLine("Invalid credentials.");
}
Make sure to replace "myuser"
with the actual username you want to validate and "mypassword"
with the corresponding password.
Note that the System.DirectoryServices.AccountManagement
namespace requires the System.DirectoryServices.AccountManagement
NuGet package. You may need to add this package to your project if it's not already included.
This approach allows you to validate local Windows account credentials in .NET Core 3.1.