本文提供了一个引导步骤,讲解了如何在WCF解决方案中采用WCS作为身份验证方式。本文假设你已经清楚地了解了WCF的各项机制。
第一部分:服务部分
1. 服务契约
using System.ServiceModel;
namespace HelloService
{
[ServiceContract]
public interface IHello
{
[OperationContract]
string Say();
}
}
2. 服务实现和宿主程序
需要预先引用System.ServiceModel,System.IdentityModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
namespace HelloService
{
class Hello : IHello
{
#region IHello 成员
public string Say()
{
GetIdentity();
return "Hello,World";
}
private void GetIdentity()
{
AuthorizationContext ctx =
OperationContext.Current.ServiceSecurityContext.AuthorizationContext;
foreach (ClaimSet claimSet in ctx.ClaimSets)
{
foreach (Claim claim in claimSet)
{
Console.WriteLine();
Console.WriteLine("ClaimType: " + claim.ClaimType);
Console.WriteLine("Resource: " + claim.Resource);
Console.WriteLine("Right: " + claim.Right);
}
}
return;
}
#endregion
}
class Program
{
static void Main(string[] args)
{
ServiceHost sh = new ServiceHost(typeof(Hello), new Uri("http://localhost:4123/helloService"));
sh.Open();
Console.WriteLine("Service listening...");
Console.WriteLine("Press
to finish"
);
Console.ReadLine();
sh.Close(); // close the service
}
}
}
代码中的GetIdentity方法是我们自己写的,主要是为了解析Windows Cardspace传递过来的凭据信息。
3. 服务配置
xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service
name="HelloService.Hello"
behaviorConfiguration="helloServiceBehavior">
<endpoint
address="helloEndpoint"
contract="HelloService.IHello"
binding="wsFederationHttpBinding"
bindingConfiguration="helloFederatedBinding">
<identity>
<certificateReference
findValue="WCFTestCert"
storeLocation="CurrentUser"
storeName="My"
x509FindType="FindBySubjectName" />
identity>
endpoint>
<</