gpt4 book ai didi

c# - 如何通过使用 C# 传递凭据在服务器上创建文件夹

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:42 25 4
gpt4 key购买 nike

我正在使用 C# 开发一个 ASP.NET 应用程序,它试图通过登录然后将文件写入本地驱动器来从网站读取一些文件。

我已经通过网络凭据通过读取默认凭据登录网站 -

request.Proxy.Credentials = CredentialCache.DefaultCredentials;

现在我想将文件存储在需要一些凭据才能访问该位置的服务器目录中。

网站登录代码-

                string webUrl = "https://web.site.com/";

string formParams = string.Format("user={0}&password={1}", username, password);

WebRequest req = WebRequest.Create(webUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();

cookieHeader = resp.Headers["Set-cookie"];

位置是\\11.11.11.11\Folder\

如何传递访问该位置的凭据?我已经了解了 impersonation 但到目前为止没有得到任何帮助。我有可以访问该位置的凭据。但是我如何使用 C# 代码来做到这一点?

提前致谢:)

最佳答案

您可以使用 LogonUser用于此的 API。您使用 LogonUser 函数创建一个 token ,代表您要模拟的 WindowsIdentity。然后您使用 token 创建一个 WindowsIdentity 并调用 Impersonate身份上。后面的所有代码都在模拟身份下运行。

确保你总是Undo WindowsImpersonationContext .

[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain,
string lpszPassword, int dwLogonType,
int dwLogonProvider, out IntPtr phToken);

[DllImport("advapi32.dll", SetLastError=true)]
public extern static bool DuplicateToken(
IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL,
out IntPtr DuplicateTokenHandle);

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool CloseHandle(IntPtr hHandle);

const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_PROVIDER_DEFAULT = 0;
IntPtr hToken;
IntPtr hTokenDuplicate;

if (LogonUser(username, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out hToken))
{
if (DuplicateToken(hToken, 2, out hTokenDuplicate))
{
WindowsIdentity windowsIdentity = new WindowsIdentity(hTokenDuplicate);
WindowsImpersonationContext impersonationContext =
windowsIdentity.Impersonate();
try
{
// Access files ...
// ...
}
finally
{
impersonationContext.Undo();
if (hToken != IntPtr.Zero) CloseHandle(hToken);
if (hTokenDuplicate != IntPtr.Zero) CloseHandle(hTokenDuplicate);
}
}
}

关于c# - 如何通过使用 C# 传递凭据在服务器上创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11306542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com