Popular Posts
ListSelectionListener & ItemListener import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ItemEvent; import java.awt.event.ItemL... netbean shortcut Ctrl + F:尋找 F3:尋找下一個字串 Ctrl + G:跳到第 N 行 Ctrl + H:取代 Tab:增加縮排 Shift + Tab:減少縮排 Ctrl + E:刪除一行 Ctrl + Shift + I:修正 import 項目 Alt + Ent... Capture response output stream using HttpModule using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; namespace TestWebA...
Blog Archive
Stats
Active Directory authentication
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

class Program
{
    static void Main(string[] args)
    {
        string domain = "mydomain";
        string account = "bruce";
        string password = "12345678";

        Console.WriteLine(IsAuthenticated1(domain, account, password));
        Console.WriteLine(IsAuthenticated2(domain, account, password));
        Console.WriteLine(IsAuthenticated3(domain, account, password));
        Console.Read();
    }

    static bool IsAuthenticated1(string domain, string account, string password)
    {
        bool isAuthenticated = false;
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
        try
        {
            object o = entry.NativeObject;
            isAuthenticated = true;
            entry.Close();
        }
        catch (Exception ex)
        {
            entry.Close();
        }
        return isAuthenticated;
    }

    static bool IsAuthenticated2(string domain, string account, string password)
    {
        bool isAuthenticated = false;
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
        try
        {
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = string.Format("(sAMAccountName={0})", account);
            SearchResult result = searcher.FindOne();
            entry.Close();
            isAuthenticated = true;
        }
        catch (Exception ex)
        {
            entry.Close();
        }
        return isAuthenticated;
    }

    static bool IsAuthenticated3(string domain, string account, string password)
    {
        try
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
            return pc.ValidateCredentials(account, password);
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}