如何发送凭据来调用服务?

时间:2014-01-18 14:06:44

标签: .net wcf c#-4.0

何以进行基本身份验证或将凭据信息发送给服务?

我已在解决方案中添加了服务引用(JAVA服务引用)。当我试图打电话给服务时,它会发出一个错误,说明未经授权的服务请求。如何在呼叫服务时发送凭据?我在登录窗口输入用户名和密码后,应立即发送凭证以呼叫服务。 我是WCF的新手,我之前使用过asmx程序。我可以这样做吗?

public partial class Program
{


    static void Main(string[] args)
    {

        ServiceReference2.ESIVisServicePortTypeClient client = new ServiceReference2.ESIVisServicePortTypeClient();

        ServiceReference2.PartType part = new ServiceReference2.PartType();
        part.partnumber = "A2040000049";
        ServiceReference2.ResponseType response = client.getPart2D(part);
        Console.WriteLine("Major: " + response.major + " Minor: " + response.minor);
    }
}

   <system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="VisualizationSoapBinding" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <!--<security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="Windows"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                </security>-->
              <security mode="TransportCredentialOnly">
                <transport clientCredentialType="Basic" realm=""/>
              </security>
            </binding>
            <binding name="VisualizationSoapBinding1" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <!--<security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="Windows"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                </security>-->
              <security mode="None">
                <transport  proxyCredentialType="Windows" realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://vissvc-test.e.corpintra.net:80/VisSvcNative/DAIESIVisService"
            binding="basicHttpBinding" bindingConfiguration="VisualizationSoapBinding1"
            contract="ServiceReference2.ESIVisServicePortType" name="ESIVisServicePort1" />
    </client>
</system.serviceModel>

在我使用的asmx中,`private void InitExt()         {

        if (this.Url == null || this.Url == "")
        {
            this.Url = ServiceConfiguration.URL;
        }
        this.AllowAutoRedirect = true;
        //3.5 change - Lambda expressions
        ServicePointManager.ServerCertificateValidationCallback +=
            (sender, certificate, chain, sslPolicyErrors) => true;

    }

    public bool Authentify(string username, string password)
    {
        if (m_boolEnableProxy.ToLower() == "true")
        {
            WebProxy px = new WebProxy("proxy", 80);
            px.Credentials = CredentialCache.DefaultCredentials;
            WebRequest.DefaultWebProxy = px;
        }

        m_strUsername = username;
        NetworkCredential _nwcAuthentify = new NetworkCredential(username, password);
        this.Credentials = _nwcAuthentify.GetCredential(new Uri(this.Url), "basic");
        return this.Credentials != null;            
    }


    public void SetEndpoint(string url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            this.Url = url;
        }
    }

    `

并获取会话cookie

 protected string GetSessionCookie()
    {
        string ret = "";
        WebResponse res;
        if (m_webRequest != null)
        {
            res = base.GetWebResponse(m_webRequest);
            if (res != null)
            {
                for (int i = 0; i < res.Headers.Keys.Count; i++)
                {
                    string key = res.Headers.Keys.Get(i);
                    string smsession = res.Headers.Get(i);
                    if (key == ServiceConfiguration.HEADER_COOKIE_NAME_C || key == ServiceConfiguration.HEADER_COOKIE_NAME_SETC || smsession.IndexOf(ServiceConfiguration.COOKIE_SMSESSION) > -1)
                    {
                        int index = smsession.IndexOf(ServiceConfiguration.COOKIE_SMSESSION) + ServiceConfiguration.COOKIE_SMSESSION.Length;
                        // Trim front
                        smsession = smsession.Substring(index);
                        index = smsession.IndexOf(ServiceConfiguration.HEADER_COOKIE_SEPARATOR);
                        // Trim end
                        ret = smsession.Substring(0, index);
                        // End loop
                        //break;
                        i = res.Headers.Keys.Count;
                    }
                }                    
            }
        }            
        return ret;
    }

    protected override WebRequest GetWebRequest(Uri uri)
    {
        //apptoken name to be sent instead of caller app name - 10.1
        this.RequestSoapContext.Addressing.From = new Uri(appToken, UriKind.Relative);     

        WebRequest req = base.GetWebRequest(uri);

        req.Headers.Add(ServiceConfiguration.HEADER_COOKIE_NAME_C, ServiceConfiguration.HEADER_COOKIE_VALUE);
        req.Method = ServiceConfiguration.REQUEST_METHOD;
        req.ContentType = ServiceConfiguration.REQUEST_CONTENT_TYPE;            
        string smsession = GetSMSessionCookie();
        if (smsession != "")
        {
            req.Headers.Add(ServiceConfiguration.HEADER_COOKIE_NAME_C, smsession);
        }

        m_webRequest = req;

        return req;

    }

I am using .net 4.0 C# 2010 winforms.

1 个答案:

答案 0 :(得分:0)

根据这个MSDN article,您很可能希望做到这样的事情:

  

client.ClientCredentials.Username.Username = username;   client.ClientCredentials.Username.Password = password;