質問

が簡単に行う装ユーザーです。います。

これまでにまとめて このクラスからコードのプロジェクト すべての私の偽装条件です。

あると良いです。純させていただきます。

いユーザー資格セット(ユーザー名、パスワードを、ドメイン名)を代表する人が必要で行していた

役に立ちましたか?

解決

ここでも概要です。純偽装。

基本的にするこれらのクラスのボックスできます。NETフレームワーク:

このコードでも長いものはなぜだ多くの事例のように一つの参考として単純化します。

他のヒント

"偽装"に出ます。ネットスペース"という意味で、一般的には走行コードを特定のユーザアカウントではやや別の概念によってはアクセス権を得るためにユーザーアカウントを介してユーザー名とパスワードは、この二つのアイデアのペアとします。について説明しても、その方法などの説明ができるようになっ SimpleImpersonation 図書館を利用しています。

偽装

のApiを偽装が提供されます。純の System.Security.Principal 名前:

  • 新しいコード(.純4.6+,.ネコアなど) は一般的に使用 WindowsIdentity.RunImpersonated, を受け入れるハンドルのトークンのユーザーアカウントは、次のいずれかの条件が成立する、 Action または Func<T> のためのコードを実行することを示しています。

    WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
    });
    

    または

    var result = WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
        return result;
    });
    
  • 古いコードを使用し WindowsIdentity.Impersonate 法取得 WindowsImpersonationContext オブジェクトです。このオブジェクトの実施 IDisposable, で一般的とも言うべきか using ブロックです。

    using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle))
    {
        // do whatever you want as this user.
    }
    

    このAPIが存在します。NETフレームワークで一般的に回避すべきではない。ネコます。純ます。

アクセスするユーザーアカウント

APIの利用にはユーザー名とパスワードへのアクセスユーザーアカウントのWindowsでは LogonUser -であるWin32ネイティブAPIに含まれています。により、内蔵しています。純APIを呼び出していることを、こちらの暑さにもだいぶ慣れてなリゾートへの呼び出し.

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

これは基本的な定義があまり考え、実際に利用で生産:

  • 取得の"安全"へのアクセスパターンです。
  • 閉会のネイティブを適切に取り扱う
  • コードアクセスセキュリティ(CAS)の信頼レベルです。NETフレームワークのみ)
  • SecureString できる場合の収集につ安全に経由でユーザのキーストローク.

量のコードの書き込み先を示すべての本を超えるべきでStackOverflowの回答を、まぁ.

合わせやすいアプローチ

代わりに、問い合わせすべての自分の考えを使って SimpleImpersonation 図書館は、偽装やユーザーのアクセスを単一のAPIとなります。でもでも近代以上のコードを拠点となるので、単純なAPI:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
}); 

または

var credentials = new UserCredentials(domain, username, password);
var result = Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
    return something;
});

がありますのでご注意に非常によく似て WindowsIdentity.RunImpersonated APIが必要としないのかなトークン。

このAPIのバージョン3.0.0.のプロジェクトのreadmeファイルできます。また、以前のバージョンの図書館利用したAPIに IDisposable パターンに類似す WindowsIdentity.Impersonate.の新しいバージョンは、より安全などもあるが、これらはいずれも使用します。

こうしたい:

using System.Security.Principal;
using(WindowsIdentity.GetCurrent().Impersonate())
{
     //your code goes here
}

もっぽい大人な雰囲気をより詳細にできます。なにができるの偽装、configファイルいいし、このウェブサイト、または方法デコレータ(属性)の場合は、WCFサービス、通---のアイデアです。

また、がちゃがクライアントを装うという特定のサービス(ウェブアプリ)を設定する必要があり、お客様が正しくなることを通過したときは、適切なトークン

最後に、だいたいは代理または設定の広告を正しくすることにより、ユーザーは、機械の信頼されています。

編集:
こちらの か行ユーザー様による別付けとなり、さらなる。

こちらは自vb.net ポートマット-ジョンソンの答えです。私は追加の列挙型のログオンの種類です。 LOGON32_LOGON_INTERACTIVE 最初の列挙型値るたsqlサーバーです。私の接続文字列だった信頼を得ています。ユーザ名/パスワードの接続文字列になります。

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

を使用する必要があり、 Using 述が含まれているコード実行impersonated.

ビューから更に詳細前の答え を生み出しているnugetパッケージ Nuget

コード Github

サンプル利用できる:

           string login = "";
           string domain = "";
           string password = "";

           using (UserImpersonation user = new UserImpersonation(login, domain, password))
           {
               if (user.ImpersonateValidUser())
               {
                   File.WriteAllText("test.txt", "your text");
                   Console.WriteLine("File writed");
               }
               else
               {
                   Console.WriteLine("User not connected");
               }
           }

Vieuwのフルコード:

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;


/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
    /// <summary>
    /// Logon method (check athetification) from advapi32.dll
    /// </summary>
    /// <param name="lpszUserName"></param>
    /// <param name="lpszDomain"></param>
    /// <param name="lpszPassword"></param>
    /// <param name="dwLogonType"></param>
    /// <param name="dwLogonProvider"></param>
    /// <param name="phToken"></param>
    /// <returns></returns>
    [DllImport("advapi32.dll")]
    private static extern bool LogonUser(String lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

    /// <summary>
    /// Close
    /// </summary>
    /// <param name="handle"></param>
    /// <returns></returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    private WindowsImpersonationContext _windowsImpersonationContext;
    private IntPtr _tokenHandle;
    private string _userName;
    private string _domain;
    private string _passWord;

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

    /// <summary>
    /// Initialize a UserImpersonation
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="domain"></param>
    /// <param name="passWord"></param>
    public UserImpersonation(string userName, string domain, string passWord)
    {
        _userName = userName;
        _domain = domain;
        _passWord = passWord;
    }

    /// <summary>
    /// Valiate the user inforamtion
    /// </summary>
    /// <returns></returns>
    public bool ImpersonateValidUser()
    {
        bool returnValue = LogonUser(_userName, _domain, _passWord,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref _tokenHandle);

        if (false == returnValue)
        {
            return false;
        }

        WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
        _windowsImpersonationContext = newId.Impersonate();
        return true;
    }

    #region IDisposable Members

    /// <summary>
    /// Dispose the UserImpersonation connection
    /// </summary>
    public void Dispose()
    {
        if (_windowsImpersonationContext != null)
            _windowsImpersonationContext.Undo();
        if (_tokenHandle != IntPtr.Zero)
            CloseHandle(_tokenHandle);
    }

    #endregion
}

私が認識していただき、また近の者がしたいと考えての図書館から フィリップアラン-Harding, では、ひとつひとつこの場合と同様です。

だけのようなコードです:

private const string LOGIN = "mamy";
private const string DOMAIN = "mongo";
private const string PASSWORD = "HelloMongo2017";

private void DBConnection()
{
    using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))
    {
    }
}

と追加のクラス:

.ネット(C#)偽装とネットワーク資格

私の例できる場合に使用されることが必要となるimpersonatedログオンしてネットワーク資格があります。

利用することができます。(使用nugetパッケージ) ソースコードは以下からご覧いただけます。Github:https://github.com/michelcedric/UserImpersonation

詳細 https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top