Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9366

LDAP でユーザー認証

$
0
0

.NET Framework の LdapConnection を使って、LDAP でユーザー認証するサンプルコード。
このままだと、この DN 直下にいるユーザーでのみ認証できる。
DN を固定せず認証したい場合は、一旦 LDAP を検索可能かつ DN が判明しているアカウントでバインドしてユーザー名を検索したのち、そうして得た認証対象ユーザーの DN とパスワードを使ってバインドしてみる、って流れになる。

usingSystem;usingSystem.DirectoryServices.Protocols;usingSystem.Text.RegularExpressions;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Net;namespaceLdapTest{publicstaticclassLdapAuthnTest{/// <summary>/// LDAP で認証する。/// </summary>/// <param name="userId">ユーザー名</param>/// <param name="userPassword">ユーザーのパスワード</param>/// <param name="userAttr">DN に指定されている属性 (多くの場合、CN)</param>/// <param name="baseDN">ベース DN</param>/// <param name="ldapServer">LDAP サーバーのホスト名または IP アドレス</param>/// <param name="isTls">LDAPS にする場合 true。LDAP のままにする場合 false。</param>/// <returns>認証成功でそのユーザーの <see cref="SearchResultEntry" />、認証失敗は null。</returns>/// <exception cref="LdapException">LDAP 例外</exception>publicstaticSearchResultEntryLdapAuthn(stringuserId,stringuserPassword,stringuserAttr,stringbaseDN,stringldapServer,boolisTls){// 認証情報が空の場合は即認証失敗if(userId.Length<1||userPassword.Length<1){returnnull;}ldapServer=ServerPortSpecify(ldapServer,isTls);LdapConnectionldapConnection=newLdapConnection(ldapServer){Credential=newNetworkCredential(userAttr+"="+LdapEscape(userId)+","+baseDN,userPassword),AuthType=AuthType.Basic,Timeout=newTimeSpan(0,0,10)};ldapConnection.SessionOptions.ProtocolVersion=3;ldapConnection.SessionOptions.SecureSocketLayer=isTls;SearchResultEntrysearchResultEntry=null;try{// 認証したいユーザーでバインドしてみるldapConnection.Bind();// バインドが通ったらユーザー情報を得るSearchRequestsearchRequest=newSearchRequest(){DistinguishedName=baseDN,Filter="("+userAttr+"="+userId+")"};SearchResponsesearchResponse=ldapConnection.SendRequest(searchRequest)asSearchResponse;if(searchResponse.Entries.Count==1){foreach(SearchResultEntryiteminsearchResponse.Entries){searchResultEntry=item;break;}}if(searchResultEntry==null){// 念のため。この例外がスローされることはない。thrownewArgumentOutOfRangeException(searchResponse.Entries.Count.ToString());}}catch(LdapExceptione){if(e.ErrorCode!=49)// エラー コード 49 は「認証失敗」{throwe;}else{System.Diagnostics.Debug.WriteLine(e.Message);System.Diagnostics.Debug.WriteLine(e.ServerErrorMessage);}}finally{if(ldapConnection!=null){try{ldapConnection.Dispose();}catch(Exceptione){System.Diagnostics.Debug.WriteLine(e);}}}returnsearchResultEntry;}/// <summary>/// TCP ポート指定なし、かつ、LDAPS のときはポート指定「:636」を追加する。/// </summary>/// <param name="ldapServer">LDAP サーバー指定</param>privatestaticstringServerPortSpecify(stringldapServer,boolisTls){if(isTls&&!Regex.IsMatch(ldapServer,":[0-9]*$"))returnldapServer+":636";elsereturnldapServer;}/// <summary>/// 正常に処理できるよう、特殊文字をエスケープする。(RFC2253)/// </summary>/// <param name="ldapValue">エスケープ処理前の文字列</param>/// <returns>エスケープ処理済みの文字列</returns>staticstringLdapEscape(stringldapValue){return"\""+ldapValue.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";}}}

Viewing all articles
Browse latest Browse all 9366

Latest Images

Trending Articles