2014-01-08 134 views
1

我需要一些C#代碼來驗證Windows憑據,該帳戶可能是本地帳戶或域帳戶。Windows憑據驗證

請給出一些關於如何做到這一點的想法。

+1

想法 - 使用您最喜愛的搜索引擎(Google,Bing,...)並鍵入您的文章標題。 –

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

4

取決於您使用的.NET版本。如果您使用的是.NET版本包含System.DirectoryServices.AccountManagement你可以做到以下幾點:

bool valid = false; 

using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) 
{ 
    valid = context.ValidateCredentials(username, password); 
} 

變化ContextType.Domain到ContextType.Machine本地機器。您還可以嘗試通過查詢Active Directory來模擬用戶,或嘗試使用類似的方式強制登錄本地系統。但我會推薦上述方法。

public bool IsAuthenticated(string server, string username, string password) 
{ 
    bool authenticated = false; 

    try 
    { 
     DirectoryEntry entry = new DirectoryEntry(server, username, password); 
     object nativeObject = entry.NativeObject; 
     authenticated = true; 
    } 
    catch (DirectoryServicesCOMException cex) 
    { 
     //not authenticated; reason why is in cex 
    } 
    catch (Exception ex) 
    { 
     //not authenticated due to some other exception [this is optional] 
    } 

    return authenticated; 
}