WCF Data Service authentication
-Is it possible to secure a WCF Data Service by using certificate-based authentication ?
-Is there a resource that describes this process ?
-Can we use Message se开发者_如何学Gocurity with a WCF Data service ?
The answer to all your questions is "yes". Below is a very informative link provided by the Patterns and Practices team at Microsoft to accomplish exactly what you are looking for.
http://msdn.microsoft.com/en-us/library/cc949005.aspx
Certificate based Authentication can be done like this:
Server side:
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
}
Client side:
Create a partial class for your database service reference (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);
}
}
Use it like this
Database db = new Database(new Uri(service));
db.ClientCertificate = CertificateUtil.GetCertificateByThumbprint(StoreName.My,
StoreLocation.LocalMachine,
"<a thumbprint>");
Private key stored on client computer, public key stored on server in Local machine/Trusted Root CA
Remember to require/negotiate client sertificate for this Site in IIS.
(Tested on WCF Data Services 5.2, VS 2012)
精彩评论