使用ASP.NET成员资格提供模拟 [英] Impersonation using ASP.NET Membership Provider

查看:172
本文介绍了使用ASP.NET成员资格提供模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义成员资格/角色提供商,由于项目将需要管理员登录,因为用户同时与查询,协助他们的本性。

I have a custom membership/roles provider, due to the nature of the project it will require admins to login as users while assisting them with queries.

现在,它很容易重新登录与选择的会员帐户管理员,但是这意味着管理员将有效地被注销。我正在寻找一种方式,让管理员来模拟用户,但很容易地随时切换回有自己的帐户。

Now, Its easy to re-log the admin in with the selected membership account, however this means that the admin will effectively be logged out. I'm looking for a way to allow admins to impersonate users yet very easily switch back to there own account at any time.

有什么建议?

推荐答案

这应该是你想要的那种东西。

This should be the sort of thing you want.

您可以调用ImpersonateValidUser方法,你想要的域帐户的用户名和密码。然后扭转它在注销。

You can call the ImpersonateValidUser method with the username and password of the domain account you want. And then reverse it on the logout.

您应该能够弯曲这跟您的自定义成员提供工作。

You should be able to bend this to work with your custom membership provider.

// Constants for impersonation
private WindowsImpersonationContext impersonationContext;
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

/// <summary>
/// Changes the account we are running under. 
/// </summary>
/// <param name="username">Username of a local admin account</param>
/// <param name="domain">Domain of the username</param>
/// <param name="password">Password of a local admin account</param>
/// <returns></returns>
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;
}

/// <summary>
/// Cancel the impersonation and revent the thread to the
/// default account. Typically DOMAIN\NETWORK_SERVICE or similar.
/// </summary>
private void UndoImpersonation()
{
    impersonationContext.Undo();
}

这篇关于使用ASP.NET成员资格提供模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆