- 1 year ago
Prompt for Windows user and password, just get the user identity
If you want to prompt the user for their Windows username and password in a C# program, you can use the System.DirectoryServices.AccountManagement
namespace to authenticate the user against the Windows domain. Here's an example:
csharpusing System;
using System.DirectoryServices.AccountManagement;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Prompt the user for their Windows username and password
Console.Write("Username: ");
string username = Console.ReadLine();
Console.Write("Password: ");
string password = GetPasswordFromConsoleInput();
// Authenticate the user against the domain
using (var context = new PrincipalContext(ContextType.Domain))
{
bool isAuthenticated = context.ValidateCredentials(username, password);
if (isAuthenticated)
{
Console.WriteLine($"Authenticated as {username}");
}
else
{
Console.WriteLine("Authentication failed");
}
}
}
static string GetPasswordFromConsoleInput()
{
string password = "";
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else if (key.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password = password.Substring(0, password.Length - 1);
Console.Write("\b \b");
}
}
else
{
password += key.KeyChar;
Console.Write("*");
}
}
return password;
}
}
}
This code prompts the user for their Windows username and password, and then uses System.DirectoryServices.AccountManagement.PrincipalContext
to authenticate the user against the domain. If the user is authenticated, the code outputs a message indicating the username. Note that this code assumes that the user is running on a Windows machine and is authenticated against a Windows domain.
Note that the GetPasswordFromConsoleInput()
method is used to securely read the password from the console input without displaying it on the screen.