SUPERCAT.DEV

Benvenut* sul mio blog

CSHARP

Accesso tramite utente windows

14-07-2023

Windows Authentication in app console C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices.AccountManagement;
using System.Security;

namespace wAuth
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write($"{"Nome utente:", 12}");
            string nomeutente = Win.Autenticazione.Console.ReadPassword();
            Console.Write($"{"Password:",12}");
            string pwd = Win.Autenticazione.Console.ReadPassword();

            PrincipalContext pcon = new PrincipalContext(ContextType.Domain);
            if (pcon.ValidateCredentials(nomeutente, pwd, ContextOptions.Negotiate))
            {
                Console.WriteLine("Autenticato");
            }
            else
            {
                Console.WriteLine("Non autenticato");
            }

            Console.ReadLine();
        }
    }
}

namespace Win.Autenticazione
{
    static public class Console
    {
        public static string ReadPassword(char mask)
        {
            const int ENTER = 13, BACKSPACE = 8, CTRLBACKSPACE = 127;
            int[] FILTERED = { 0, 27, 9, 10 }; 

            var pass = new Stack<char>();
            char chr = (char)0;

            while ((chr = System.Console.ReadKey(true).KeyChar) != ENTER)
            {
                if (chr == BACKSPACE)
                {
                    if (pass.Count > 0)
                    {
                        System.Console.Write("\b \b");
                        pass.Pop();
                    }
                }
                else if (chr == CTRLBACKSPACE)
                {
                    while (pass.Count > 0)
                    {
                        System.Console.Write("\b \b");
                        pass.Pop();
                    }
                }
                else if (FILTERED.Count(x => chr == x) > 0) { }
                else
                {
                    pass.Push((char)chr);
                    System.Console.Write(mask);
                }
            }

            System.Console.WriteLine();

            return new string(pass.Reverse().ToArray());
        }

        public static string ReadPassword()
        {
            return Win.Autenticazione.Console.ReadPassword('*');
        }
    }
}