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("用户名或密码错误。");
}
}
}
}
WCF中使用自定义“用户名/密码”验证
最新推荐文章于 2017-07-10 10:04:00 发布