WCF数据服务身份验证
答
对所有问题的回答是“是”。下面是Microsoft的模式和实践团队提供的一个非常丰富的链接,可以完全满足您的需求。
基于
答
证书认证可以做这样的:
服务器端:
public class ODataService : DataService<Database>
{
public ODataService()
{
ProcessingPipeline.ProcessingRequest += ProcessingPipeline_ProcessingRequest;
}
void ProcessingPipeline_ProcessingRequest(object sender, DataServiceProcessingPipelineEventArgs e)
{
if (!HttpContext.Current.Request.ClientCertificate.IsPresent)
{
throw new DataServiceException(401, "401 Unauthorized");
}
var cert = new X509Certificate2(HttpContext.Current.Request.ClientCertificate.Certificate);
if (!ValidateCertificate(cert))
{
throw new DataServiceException(401, "401 Unauthorized");
}
var identity = new GenericIdentity(cert.Subject, "ClientCertificate");
var principal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}
private bool ValidateCertificate(X509Certificate2 cert)
{
// do some validation
}
客户端:
为数据库创建服务引用的部分类(DataServiceContext )
public partial class Database
{
// ref: http://social.msdn.microsoft.com/Forums/en-US/0aa2a875-fd59-4f3e-a459-9f604b374749/how-do-i-use-certificate-based-authentication-with-data-services-client?forum=adodotnetdataservices
private X509Certificate clientCertificate = null;
public X509Certificate ClientCertificate
{
get
{
return clientCertificate;
}
set
{
if (value == null)
{
// if the event has been hooked up before, we should remove it
if (clientCertificate != null)
{
SendingRequest -= OnSendingRequest_AddCertificate;
}
}
else
{
// hook up the event if its being set to something non-null
if (clientCertificate == null)
{
SendingRequest += OnSendingRequest_AddCertificate;
}
}
clientCertificate = value;
}
}
private void OnSendingRequest_AddCertificate(object sender, SendingRequestEventArgs args)
{
if (null != ClientCertificate)
{
(args.Request as HttpWebRequest).ClientCertificates.Add(ClientCertificate);
}
}
使用方法如下
Database db = new Database(new Uri(service));
db.ClientCertificate = CertificateUtil.GetCertificateByThumbprint(StoreName.My,
StoreLocation.LocalMachine,
"<a thumbprint>");
私有密钥存储在客户计算机上,存储在服务器本地机/受信任的根CA
公钥记住需要/洽谈的客户sertificate该网站在IIS中。
(测试WCF数据服务5.2,VS 2012)
是的,但你将需要使用WS- *绑定得到消息级安全性。确保你的客户端可以使用WS *标准。我认为它在.NET 3.0及更高版本中受支持。 Silverlight不支持这一点。 – 2011-04-06 11:59:46