WCF中使用自定义“用户名/密码”验证

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;

namespace TestWcfApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(DemoService));
            // 设置自定义验证器
            host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
            host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustUsernamepwdValidator();
            // 设置证书
            host.Credentials.ServiceCertificate.SetCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My);

            // 添加终结点
            WSHttpBinding binding = new WSHttpBinding(SecurityMode.Message);
            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            host.AddServiceEndpoint(typeof(IDemo), binding, "http://localhost:7000");

            // 启动服务
            host.Opened += (f, x) => Console.WriteLine("服务已经启动。");
            try
            {
                host.Open();

                // 准备调用服务
                Console.WriteLine("============================");
                Console.WriteLine("请输入用户名。");
                string usName = Console.ReadLine();
                Console.WriteLine("请输入密码。");
                string passWord = Console.ReadLine();

                EndpointAddress epaddr = new EndpointAddress("http://localhost:7000");
                // 为了保险,终结点地址可以加上DNS标识
                // EndpointAddress epaddr = new EndpointAddress(new Uri("http://...."), EndpointIdentity.CreateDnsIdentity("localhost"));
                ChannelFactory<IDemo> fac = new ChannelFactory<IDemo>(binding, epaddr);
                // 以下设置可以忽略客户端对服务器证书的信任验证
                fac.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                // 设置用户名和密码
                fac.Credentials.UserName.UserName = usName;
                fac.Credentials.UserName.Password = passWord;

                // 调用服务
                IDemo c = fac.CreateChannel();
                c.SaySomething("你好");
                // 关闭
                fac.Close();
            }
            catch (Exception fex)
            {
                Console.WriteLine(fex.Message);
                Exception innerEx = fex.InnerException;
                while (innerEx != null)
                {
                    Console.WriteLine(innerEx.Message);
                    innerEx = innerEx.InnerException;
                }
            }

            Console.Read();
            // 关闭服务
            if (host.State == CommunicationState.Opened)
            {
                host.Close();
            }
        }
    }

    [ServiceContract]
    public interface IDemo
    {
        [OperationContract]
        void SaySomething(string msg);
    }

    //[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class DemoService : IDemo
    {
        public void SaySomething(string msg)
        {
            string outstr = string.Format("服务被调用,传入消息:{0}", msg);
            Console.WriteLine(outstr);
        }
    }

    public class CustUsernamepwdValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName != "admin" || password != "321")
            {
                throw new Exception("用户名或密码错误。");
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值