1

我有一个 Web 服务(旧的 Web 服务,而不是 WCF),并且我正在使用 IIS 7.0 与该 Web 服务进行通信。IIS 7.0 中仅启用了 Windows 身份验证(甚至禁用了匿名)。在进行服务调用时,我需要能够在代码中指定特定的 Windows 身份。我发现很多地方表明这可以通过以下方式在配置文件中完成......

<authentication mode="Windows" />
<identity impersonate="true" userName="UserName" password="P@ssw0rd" />

但我需要在代码中做同样的事情。我相信很多人都在想“你为什么要那样做”。无需进行冗长的解释,最简单的答案是因为这些是我的要求。

这是我的代码的样子......

HttpTransportBindingElement transport = useHttps ? new HttpsTransportBindingElement() : new HttpTransportBindingElement();
transport.ManualAddressing = false;
transport.MaxBufferPoolSize = 134217728; // 128MB
transport.MaxReceivedMessageSize = 134217728; // 128MB
transport.AllowCookies = false;
transport.AuthenticationScheme = AuthenticationSchemes.Negotiate;
transport.BypassProxyOnLocal = false;
transport.DecompressionEnabled = true;
transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
transport.KeepAliveEnabled = true;
transport.MaxBufferSize = 134217728; // 128MB,
transport.ProxyAuthenticationScheme = AuthenticationSchemes.Negotiate;
transport.Realm = "";
transport.TransferMode = TransferMode.Buffered;
transport.UnsafeConnectionNtlmAuthentication = false;
transport.UseDefaultWebProxy = false;

TextMessageEncodingBindingElement encoding = new TextMessageEncodingBindingElement
{
    MaxReadPoolSize = 64,
    MaxWritePoolSize = 16,
    MessageVersion = MessageVersion.Soap12,
    WriteEncoding = Encoding.UTF8,
    ReaderQuotas = new XmlDictionaryReaderQuotas
    {
        MaxDepth = 32,
        MaxStringContentLength = 134217728, // 128MB
        MaxArrayLength = 134217728, // 128MB
        MaxBytesPerRead = 4096,
        MaxNameTableCharCount = 16384
    }
};

CustomBinding binding = new CustomBinding();
binding.Elements.Add(encoding);
binding.Elements.Add(transport);

ServicePointManager.Expect100Continue = false;

generalSoapClient general = new generalSoapClient(binding, new EndpointAddress("http://localhost/site/ws/general.asmx"));
NetworkCredential iisCredentials = new NetworkCredential("UserName", "P@ssw0rd");
general.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
general.ClientCredentials.Windows.ClientCredential = iisCredentials;
string session = general.CreateDomainUserSessionFromInstance();

客户端的 .config 文件中没有定义任何内容。一切都在代码中配置。

我的 Web 服务方法如下所示(缺少一些与身份验证无关的代码)...

[WebMethod(EnableSession = true)]
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public string CreateDomainUserSessionFromInstance()
{
    if(HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
    {
        WindowsIdentityRequest authenticationRequest = new WindowsIdentityRequest(instanceName, HttpContext.Current.User.Identity as WindowsIdentity);
        response = authManager.Login(authenticationRequest);
    }

    return response.SessionContext.SessionToken;
}

我在服务器端的 web.config 看起来像这样......

<system.web>
    <authentication mode="Windows" />
    <identity impersonate="true" />
    <authorization>
        <!--<allow users="*" />-->
        <deny users="?" />
    </authorization>
</system.web>

<customBinding>
    <binding name="textHttpBinding" receiveTimeout="00:05:00" sendTimeout="00:05:00">
      <textMessageEncoding>
        <readerQuotas maxArrayLength="1024000000" maxStringContentLength="1024000000" />
      </textMessageEncoding>
      <httpTransport maxReceivedMessageSize="1024000000" maxBufferSize="1024000000" authenticationScheme="Negotiate" />
  </customBinding>

当我<deny users="?" />遇到以下错误时...“ HTTP请求未经授权,客户端身份验证方案'Negotiate'。从服务器收到的身份验证标头是'' ”有人告诉我应该是<allow users="*" />,但是当我这样做时,我可以进入网络服务,但它HttpContext.Current.User.Identity.IsAuthenticated是错误的并且.Name是空的,我在互联网上读到的是它需要deny users="?" />拒绝匿名访问。

我是 Web 服务的新手,所以不幸的是,大部分代码对我来说都是希腊语。我们的 Web 服务最初允许匿名身份验证,但要求已更改为需要 Windows 身份验证。

我花了几天时间阅读许多网站,试图正确配置所有内容,但似乎找不到正确的组合。
我究竟做错了什么?这是简单的事情还是我离谱?

4

1 回答 1

1

这是我用来模拟的一个类:

public class Impersonator :
    IDisposable
{
    private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;


    public Impersonator(
        string userName,
        string domainName,
        string password )
    {
        ImpersonateValidUser( userName, domainName, password );
    }


    public void Dispose()
    {
        UndoImpersonation();
    }


    #region P/Invoke.
    // ------------------------------------------------------------------

    [DllImport("advapi32.dll", SetLastError=true)]
    private static extern int LogonUser(
        string lpszUserName,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

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

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

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

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


    #region Private member.
    // ------------------------------------------------------------------

    /// <summary>
    /// Does the actual impersonation.
    /// </summary>
    /// <param name="userName">The name of the user to act as.</param>
    /// <param name="domainName">The domain name of the user to act as.</param>
    /// <param name="password">The password of the user to act as.</param>
    private void ImpersonateValidUser(
        string userName, 
        string domain, 
        string password )
    {
        WindowsIdentity tempWindowsIdentity = null;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        try
        {
            if ( RevertToSelf() )
            {
                if ( LogonUser(
                    userName, 
                    domain, 
                    password,
                    LOGON32_LOGON_NEW_CREDENTIALS,
                    LOGON32_PROVIDER_DEFAULT, 
                    ref token ) != 0 )
                {
                    if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
                    {
                        tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
                        impersonationContext = tempWindowsIdentity.Impersonate();
                    }
                    else
                    {
                        throw new Win32Exception( Marshal.GetLastWin32Error() );
                    }
                }
                else
                {
                    throw new Win32Exception( Marshal.GetLastWin32Error() );
                }
            }
            else
            {
                throw new Win32Exception( Marshal.GetLastWin32Error() );
            }
        }
        finally
        {
            if ( token!= IntPtr.Zero )
            {
                CloseHandle( token );
            }
            if ( tokenDuplicate!=IntPtr.Zero )
            {
                CloseHandle( tokenDuplicate );
            }
        }
    }

    /// <summary>
    /// Reverts the impersonation.
    /// </summary>
    private void UndoImpersonation()
    {
        if ( impersonationContext.IsNotNull() )
        {
            impersonationContext.Undo();
        }   
    }

    private WindowsImpersonationContext impersonationContext = null;

    // ------------------------------------------------------------------
    #endregion
}
于 2013-01-15T19:25:19.010 回答