Popular Posts
Statement.executeBatch() always returns an array of value -2 The elements in the array returned by the method executeBatch may be one of the following: A number greater than or equal to zero -- indi... vi hot key guide 第一部份:一般模式可用的按鈕說明,游標移動、複製貼上、搜尋取代等 移動游標的方法 h 或 向左方向鍵(←) 游標向左移動一個字元 j 或 向下方向鍵(↓) 游標向下移動一個字元 k 或 向上方向鍵(↑) 游標向上移動一個字元 l 或 向右方向鍵(→) 游標... Expression in polymer Since Polymer doesn't support expression directly, I create an express function as expression alternative. Demo Demo source <htm...
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;
        }
    }
}