简体   繁体   English

指定用于WCF身份验证的凭据

[英]Specifying Credentials for WCF Authentication

I have a WinForms + WCF + SQL application which I'm trying to secure using the built-in WCF security capabilities. 我有一个WinForms + WCF + SQL应用程序,我正在尝试使用内置的WCF安全功能进行保护。

I am in a position where I need to use UserName security so on the client side I understand that any time I create a proxy or a channel, I'll need to specify the ClientCredentials . 我处于需要使用UserName安全性的位置,因此在客户端,我了解到每次创建代理或通道时,都需要指定ClientCredentials

Currently the WCF calls are made like this throughout the client: 当前,WCF调用在整个客户端中都是这样的:

private void button1_Click(System.Object sender, System.EventArgs e)
{
    ServiceReference1.Service1Client client = new
        ServiceReference1.Service1Client();
    string returnString;

    returnString = client.GetData(textBox1.Text);
    label1.Text = returnString;
}

What would the best approach here be? 最好的方法是什么? Should I go through every instantiation of the proxy in the client code and set the ClientCredentials property? 我是否应该检查客户端代码中代理的每个实例,并设置ClientCredentials属性? The alternative I've thought of is specifying the credentials once in a ChannelFactory and passing the ChannelFactory around the application. 我想到的替代方法是在ChannelFactory指定一次凭据,然后在应用程序周围传递ChannelFactory Both methods seem to require a lot of rework or duplication which makes me feel like I'm being oblivious to something. 两种方法似乎都需要大量的返工或重复,这让我觉得自己对某些事情忘了。

You can implement IClientMessageInspector to include user credential on each outgoing message. 您可以实现IClientMessageInspector以在每个传出消息中包括用户凭证。

public class ClientMessageInspector : IClientMessageInspector
    {
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var credHeader = new YourCustomHeader
            {
                UserName = "UserName",
                Password = "Password"
            };

            var typedHeader = new MessageHeader<CustomHeader>(credHeader);
            var untypedHeader = typedHeader.GetUntypedHeader("custom-header", "s");

            request.Headers.Add(untypedHeader);
            return null;
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            //
        }
    }

IClientMessageInspector Interface IClientMessageInspector接口

Accessing clientcredential properties from client message inspector 从客户端消息检查器访问clientcredential属性

Creating Custom WCF Endpoint Behavior 创建自定义WCF端点行为

Consuming a web service using digest authentication 使用摘要身份验证消耗Web服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM