WCF Rest自托管证书安全服务返回未经授权的401

时间:2019-12-28 08:58:56

标签: c# wcf authentication ssl-certificate webhttpbinding

我想创建一个自托管的WCF控制台-使用证书的服务器端身份验证-其余服务。

由于我总是收到响应401未经授权,因此我在实际调用服务时遇到了问题。

由于这是“单向”身份验证,服务在向客户端标识自己,所以为什么我总是作为客户端应用程序获得401未经授权的响应(好像客户端需要向服务标识自己一样)访问其资源?)

有人能帮助我找到问题所在,以及如何使我的客户服务通信最终正常工作吗?

简单服务合同:

[ServiceContract]
public interface IService1
{

    [OperationContract]
    [WebGet(UriTemplate = "Students", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    List<Student> GetStudentDetails();

    // TODO: Add GetMethod with parameter 
    [OperationContract]
    [WebGet(UriTemplate = "Student/{id}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    Student GetStudentWithId(string id);

    //TODO: add one post method here
    [OperationContract]
    [WebInvoke(Method="POST", UriTemplate = "Student/New", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    void NewStudent(Stream stream);

    //TODO: add one post method here
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "Student/NewS", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    void NewStudentS(Student stream);
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class Student
{
    [DataMember]
    public int ID
    {
        get;
        set;
    }

    [DataMember]
    public string Name
    {
        get;
        set;
    }
}

服务实施:

public class Service1 : IService1
{
    public List<Student> GetStudentDetails()
    {
        return new List<Student>() { new Student() { ID = 1, Name = "Goran" } };
    }

    public Student GetStudentWithId(string id)
    {
        return new Student() { ID = Int32.Parse(id), Name = "Ticbra RanGo" };
    }

    public void NewStudent(Stream stream)
    {
        using(stream)
        {
            // convert Stream Data to StreamReader
            StreamReader reader = new StreamReader(stream);
            var dataString = reader.ReadToEnd();

            Console.WriteLine(dataString);
        }
    }

    public void NewStudentS(Student student)
    {
        Console.WriteLine(student.Name);
    }
}

运行服务的控制台应用程序:

static void Main(string[] args)
    {
        Uri httpUrl = new Uri("https://localhost:8080/TestService");
        using (WebServiceHost host = new WebServiceHost(typeof(Service1)))
        {
             // Create the binding.  
            WSHttpBinding binding = new WSHttpBinding();
            binding.Name = "binding1";
            binding.Security.Mode = SecurityMode.Transport;


            host.AddServiceEndpoint(typeof(IService1), binding, httpUrl/*"rest"*/);
            // Enable metadata publishing.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);              

            //Add host certificate to service wcf for identification
            host.Credentials.ServiceCertificate.SetCertificate(
                StoreLocation.LocalMachine,
                StoreName.My,
                X509FindType.FindBySubjectName,
                "localhost");

            host.Open();

            foreach (ServiceEndpoint se in host.Description.Endpoints)
                Console.WriteLine("Service is host with endpoint " + se.Address);

            Console.WriteLine("Host is running... Press < Enter > key to stop");
            Console.ReadLine();
            host.Close();
        }

        //Console.WriteLine("ASP.Net : " + ServiceHostingEnvironment.AspNetCompatibilityEnabled);
        Console.WriteLine("Host is running... Press < Enter > key to stop");
        Console.ReadLine();
    }

请注意,我通过KeyStore Explorer创建了证书根目录和子目录,并将它们适当地放在Windows上的个人和受信任的根证书中。 Certificates

我通过CMD将服务器证书映射到端口8080。

我使用的客户端是SOAPUI,而我的手动编码客户端。 客户代码:

        WebRequest request = HttpWebRequest.Create(urlTextBox.Text);

        var webResponse = request.GetResponse();

        using (Stream dataStream = webResponse.GetResponseStream())
        {
            // Open the stream using a StreamReader for easy access.  
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            // Display the content.  
            Console.WriteLine(responseFromServer);
            HttpResonseTextBox.Text = responseFromServer;
        }

致以最诚挚的谢意,谢谢您

2 个答案:

答案 0 :(得分:0)

您正在将证书映射到端口8080,以使https协议正常工作。 直到这一刻都没事。

但是401错误意味着服务需要客户端提供一些凭据(如果存在则引发401错误)

请尝试删除(或注释)如下所示的SetCertificate方法调用

           //Add host certificate to service wcf for identification
            //host.Credentials.ServiceCertificate.SetCertificate(
            //    StoreLocation.LocalMachine,
            //    StoreName.My,
            //    X509FindType.FindBySubjectName,
            //    "localhost");

,请尝试它是否起作用。只是检查

带有证书的Wcf传输安全性也要求客户端like it is documented也指定证书。

我不确定您可以使用带有HttpWebRequest的soap协议的证书身份验证来使用wcf服务。它要求使用具有SetCertificate方法的wcf客户端:

// The client must specify a certificate trusted by the server.  
cc.ClientCredentials.ClientCertificate.SetCertificate(  
    StoreLocation.CurrentUser,  
    StoreName.My,  
    X509FindType.FindBySubjectName,  
    "contoso.com");  

(这是文档中的示例)

答案 1 :(得分:0)

  

WSHttpBinding绑定=新的WSHttpBinding();
              binding.Name =“ binding1”;
              binding.Security.Mode = SecurityMode.Transport;

上面的代码将Windows身份验证作为对客户端进行身份验证的方式。

        //this is the default value unless we specify it manually.
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

因此,我们应该在客户端通过提供Windows凭据来调用它。 此外,这种WCF服务不称为Rest API,而是称为SOAP Web服务。我们通常使用客户端代理来调用它。
https://docs.microsoft.com/en-us/dotnet/framework/wcf/accessing-services-using-a-wcf-client
然后设置Windows凭据并调用该方法。

            ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
            //these are windows accounts on the server-side.
            client.ClientCredentials.Windows.ClientCredential.UserName = "administrator";
            client.ClientCredentials.Windows.ClientCredential.Password = "123456";
            var result = client.Test();
            Console.WriteLine(result);

如果我们要创建休息服务,请使用Webhttp绑定来创建服务。

            WebHttpBinding binding = new WebHttpBinding();
            binding.Security.Mode = WebHttpSecurityMode.Transport;
            //this is default value. 
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

同样,我们需要将证书绑定到特定端口,以使传输层安全性可用。

  

netsh http add sslcert ipport = 0.0.0.0:8000 certhash = 0000000000003ed9cd0c315bbb6dc1c08da5e6 appid = {00112233-4455-6677-8899-AABBCCDDEEFF}

Netsh Http命令。
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-configure-a-port-with-an-ssl-certificate
因此,认证客户端的安全模式为HttpClientCredentialType.None。我们不需要在客户端提供Windows凭据。
随时让我知道是否有什么可以帮助您的。