【问题标题】:EF Code First Connection String during Runtime with Impersonated Windows Service Account运行时使用模拟 Windows 服务帐户的 EF 代码优先连接字符串
【发布时间】:2018-07-20 17:18:23
【问题描述】:
  1. 我需要为每个服务帐户创建单独的 Windows 服务帐户 我的桌面环境(开发、验收和生产) 应用程序用于连接到我们的内部数据库之一。

  2. 已将全局组添加到这些帐户以提供访问权限 从而需要通过使用模拟的 Windows 身份验证进行访问。

  3. 连接字符串数据被加密存储 在网络上,由类库访问以确保安全。

如果我不模拟,并使用接受连接字符串的DbContext 基类的基本构造函数,它可以工作,因为我的个人帐户被分配到同一个全局组。但是,当我封装 DbContext 对象的实例化以模拟时,它会失败并出现 internal exception 声明 catastrophic failureouter exception 声明

提供程序未返回 ProviderManifest 实例。

例如:

Console.WriteLine(Environment.UserName); //This shows me!  So no impersonation yet!
using (new Impersonator("AppUser", "mydomain", "notapassword"))
{
    Console.WriteLine(Environment.UserName); //This shows as AppUSER!  So it works!
    using (BillMarkContext dbContext = new BillMarkContext())
    {
        //Read each bill mark object
        foreach (BillMarkCode code in dbContext.BillMarkCodes.AsEnumerable<BillMarkCode>())
            Console.WriteLine(code.Code);
    }
}

public partial class BillMarkContext : DbContext
{
    private static string _connection = "Integrated Security=True;Persist Security Info=True;Initial Catalog=MyDB;Data Source=DBServer";

    public BillMarkContext()
        : base(_connection)
    {}

    public virtual DbSet<BillMarkCode> BillMarkCodes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {}
}

然后我尝试通过创建自己的DbConfiguration 对象来对连接信息进行硬编码,但是这会导致错误,它显然试图做的不仅仅是建立一个可读的连接。 它正在尝试创建我没有权限的数据库。

例子:

[DbConfigurationType(typeof(MyDbConfiguration))]
public partial class BillMarkContext : DbContext
{
    public BillMarkContext()
    {}

    public virtual DbSet<BillMarkCode> BillMarkCodes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {}
}

public class MyDbConfiguration : DbConfiguration
{
    public MyDbConfiguration()
    {
        SetProviderServices("System.Data.SqlClient", SqlProviderServices.Instance);
        SetDefaultConnectionFactory(new SqlConnectionFactory("Integrated Security=True;Persist Security Info=True;Initial Catalog=MyDB;Data Source=DBServer"));
    }
}

这是 Code-First,我只能使用 DbConfiguration 找到非常简单的语句和超高级示例。关于连接/提供者信息的运行时定义,信息似乎总是针对基于模型的方法,或者一直忽略提供者。

如何以编程方式配置 EF Code-First 方法以在模拟应用程序的 Windows 服务帐户时访问数据库而不出现这些错误?

【问题讨论】:

  • 您的内容太长,无法阅读。请考虑缩短它并仅提供相关信息。
  • @niksofteng 很好,但通常有人告诉我我放的不够。
  • 您有问题吗?我在任何地方都看不到问号。用底部的问题总结整个帖子总是好的。此外,如果您添加一些文本格式(粗体、斜体、项目符号等)以使前 4 段更易于视觉解析,这将有所帮助。在此处查看其他一些问题以获取想法。
  • 呃-哦,冒充。 doesn't work by default 的那个东西。我怀疑 EF Core 是否考虑过这一点,即使这样做,在最低级别 SqlConnection 也不会。而是在新的登录名下运行整个过程。
  • @JeroenMostert 这是一篇好文章。这是我第一次使用模仿,这让我大开眼界。

标签: c# .net sql-server entity-framework dbcontext


【解决方案1】:

所以,我想我终于解决了这个问题。阅读大量 MSDN 文章和许多个人博客,这是一次非常冒险的经历。在解决这个问题的过程中,我还发现了我们的数据库访问角色布局的问题。这部分仅表明确保并验证您的角色设置正确同样重要。不要只相信他们的话。我们现在已经修复了它们,但可能需要实施更多控制并确保它们以最适当的方式进行管理。我想提供我的例子来帮助处于相同情况的其他人,并为退伍军人提供一些评论,如果他们看到一些改进机会。下面的示例仍然有点幼稚,因为我可能可以围绕 SecureString 做更多的事情,但我认为这不是问题的核心。所以,就这样吧……

消费者:

    [STAThread]
    static void Main(string[] args)
    {
        try
        {
            string domain = "myDomain";
            string userName = "myUserName";
            string password = "NotAPassword"

            //Using NEW_CREDENTIALS is the same as RunAs with the /netonly switch set.  Local computer login is based on the 
            //current user.  While the impersonated account will be used for remote access to resources on the network.  
            //Therefore authentication across the domain.
            //Per MSDN, NEW_CREDENTIALS should only work with the WINNT50 provider type.  However, I have verified this to work with Default.
            //I'm just not sure of the long-term implications since MS made a point to specify this.
            using (Impersonator.LogonUser(domain, userName, password, LogonType.NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))
            {
                //This will show the currently logged on user (machine), because NEW_CREDENTIALS doesn't alter this, only remote access
                Console.WriteLine("Current user...{0}", WindowsIdentity.GetCurrent().Name);  

                using (BillMarkContext dbContext = new BillMarkContext())
                {
                    //Read each bill mark object
                    foreach (BillMarkCode code in dbContext.BillMarkCodes.AsEnumerable<BillMarkCode>())
                    {
                        Console.WriteLine(code.Code);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        Console.ReadLine();
    }

上下文:

显然,现实世界的实现不会将连接字符串存储在静态字段中。

public partial class BillMarkContext : DbContext
{
    private static string _connection4 = "Integrated Security=True;Persist Security Info=True;Initial Catalog=MyDB;Data Source=MyServer";

    public BillMarkContext()
        : base(_connection4)
    {
        //Since we're read-only
        Database.SetInitializer<BillMarkContext>(null);
    }

    //View property setup since we're read-only
    protected virtual DbSet<BillMarkCode> _billMarkCodes { get; set; }

    public DbQuery<BillMarkCode> BillMarkCodes
    {
        get { return Set<BillMarkCode>().AsNoTracking(); }
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    { }
}

模仿者和支持类/枚举:

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
internal sealed class Impersonator : IDisposable
{
    #region Properties

    private SafeTokenHandle _handle;

    private WindowsImpersonationContext _context;

    private bool _isDisposed;

    public bool IsDisposed
    {
        get { return _isDisposed; }
        private set { _isDisposed = value; }
    }

    #endregion

    #region Constructors / Factory Methods

    private Impersonator(string domain, string userName, string password, LogonType logonType, LogonProvider provider)
    {
        bool gotTokenHandle = NativeLoginMethods.LogonUser(userName, domain, password, (int)logonType, (int)provider, out _handle);

        if (!gotTokenHandle || _handle.IsInvalid)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(errorCode);
        }
    }

    public static Impersonator LogonUser(string domain, string userName, string password, LogonType logonType, LogonProvider provider)
    {
        Impersonator impersonator = new Impersonator(domain, userName, password, logonType, provider);

        impersonator._context = WindowsIdentity.Impersonate(impersonator._handle.DangerousGetHandle());

        return impersonator;
    }

    #endregion

    #region Dispose Pattern Methods

    private void Dispose(bool disposing)
    {
        //Allow the Dispose() to be called more than once
        if (this.IsDisposed)
            return;

        if (disposing)
        {
            // Cleanup managed wrappers
            if (_context != null)
                _context.Dispose();

            if (_handle != null && !_handle.IsClosed)
                _handle.Dispose();

            //Suppress future calls if successful
            this.IsDisposed = true;
        }
    }

    public void Dispose()
    {
        //Dispose the resource
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion

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

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool CloseHandle(IntPtr handle);
}

internal sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    #region Constructors

    internal SafeTokenHandle()
        : base(true)
    { }

    #endregion

    #region Support Methods

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    protected override bool ReleaseHandle()
    {
        return NativeLoginMethods.CloseHandle(base.handle);
    }

    #endregion
}

/// <summary>
/// Logon Type enum
/// </summary>
internal enum LogonType : int
{
    /// <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>
    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>
    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.
    /// </summary>
    BATCH = 4,
    /// <summary>
    /// Indicates a service-type logon. The account provided must have the service privilege enabled.
    /// </summary>
    SERVICE = 5,
    /// <summary>
    /// GINAs are no longer supported.  Windows Server 2003 and Windows XP:  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>
    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.
    /// </summary>
    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. This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
    /// </summary>
    NEW_CREDENTIALS = 9
}

internal enum LogonProvider : int
{
    /// <summary>
    /// Use the standard logon provider for the system. The default security provider is negotiate, unless you pass NULL for the domain name and the user name is not in UPN format. In this case, the default provider is NTLM.
    /// </summary>
    LOGON32_PROVIDER_DEFAULT = 0,
    /// <summary>
    /// Use the Windows NT 3.5 logon provider.
    /// </summary>
    LOGON32_PROVIDER_WINNT35 = 1,
    /// <summary>
    /// Use the NTLM logon provider.
    /// </summary>
    LOGON32_PROVIDER_WINNT40 = 2,
    /// <summary>
    /// Use the negotiate logon provider. 
    /// </summary>
    LOGON32_PROVIDER_WINNT50 = 3
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多