2

ネットワーク上にあるフォルダからファイルを読みたい。

このフォルダに手動でアクセスしようとすると(\\ ABCServer \ Documentsのようなパスを指定して実行コマンドから)、資格情報(ユーザー名とパスワード)を要求されます。正しいクレデンシャルを指定した後、ファイルにアクセス/読み取ることができます。

ASP.NETのC#コードから同じファイルを読み込もうとすると、エラーが発生します。

ログイン失敗:不明なユーザー名または不正なパスワード

ファイルの読み取り中にC#コードを介してクレデンシャルを渡すにはどうすればよいですか?

以下は私が使用しているコードの一部です:

Stream s = File.OpenRead(filePath);
byte[] buffer = new byte[s.Length];            
try
{
    s.Read(buffer, 0, (Int32)s.Length);
}            
finally 
{ 
    s.Close();
}     

ノート:

  • コードは正常に機能します
  • C#でASP.NET4.0を使用しています
  • IISのバージョンは7.5です
4

2 に答える 2

4

これはhttp://support.microsoft.com/kb/306158からのものです

public const int LOGON32_LOGON_INTERACTIVE=2;
public const int LOGON32_PROVIDER_DEFAULT=0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
    String lpszDomain,
    String lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    ref IntPtr phToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
    int impersonationLevel,
    ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

private bool impersonateValidUser(String userName, String domain, String password) {
  WindowsIdentity tempWindowsIdentity;
  IntPtr token=IntPtr.Zero;
  IntPtr tokenDuplicate=IntPtr.Zero;

  if(RevertToSelf()) {
    if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
      LOGON32_PROVIDER_DEFAULT, ref token)!=0) {
        if(DuplicateToken(token, 2, ref tokenDuplicate)!=0) {
          tempWindowsIdentity=new WindowsIdentity(tokenDuplicate);
        impersonationContext=tempWindowsIdentity.Impersonate();
        if(impersonationContext!=null) {
          CloseHandle(token);
          CloseHandle(tokenDuplicate);
          return true;
        }
      }
    }
  }
  if(token!=IntPtr.Zero)
    CloseHandle(token);
  if(tokenDuplicate!=IntPtr.Zero)
    CloseHandle(tokenDuplicate);
  return false;
}

private void undoImpersonation() {
  impersonationContext.Undo();
}
于 2012-12-17T20:05:56.583 に答える
1

これは、なりすましを使用して行うことができます。これがどのように行われるかについての質問と回答です。

于 2012-12-17T18:50:17.923 に答える