I want to use the .net class HttpListener to intercept requests to my selfhosted (WebServiceHost) WCF Data Service in order to add the "WWW-Authenticate" header to the response (for user authentication). But it seems like that the HttpListener doesn't intercept any requests that go to my dataservice. The HttpListner works for different paths just fine. Example: HttpListner Prefix: http://localhost/somePath/Works: http://localhost/somePath/Doesn't Work: http://localhost/somePath/myWCFDataService
Is it possible to intercept also requests that go to a selfhosted WCF Data Service (WebServiceHost) with the HttpListner?
Here are the relevant code snippets...
Hosting the WCF DataService:
WebServiceHost dataServiceHost = new WebServiceHost(typeof(MyWCFDataService));
WebHttpBinding binding = new WebHttpBinding();
dataServiceHost.AddServiceEndpoint(typeof(IRequestHandler), binding,
"http://localhost/somePath/myWCFDataService");
dataServiceHost.Open();
The HTTP Listner:
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add("http://localhost/somePath/");
httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
httpListener.Start();
while (true)
{
HttpListenerContext context = httpListener.GetContext();
string authorization = context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authorization))
{
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"myDataService\"");
context.Response.OutputStream.Close();
context.Response.Close();
}
}
Is there a better way for doing HTTP basic authentication within WCF Data Services? I wan't to be able to authenticate via the login dialog of the web browser.
Many thanks,
JeHo
You're barking up the wrong tree messing with proxying via HttpListener. Have a look at this.
Related
So I am currently working on making SOAP API request to a service with WCF generated code "Client object", I am wondering how to set the Cookie header to the request?
In general, we add the custom HTTP header by using HttpRequestMessageProperty. Please refer to the below code.
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
try
{
using (OperationContextScope ocs=new OperationContextScope(client.InnerChannel))
{
var requestProp = new HttpRequestMessageProperty();
requestProp.Headers["myhttpheader"] = "Boom";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProp;
var result = client.SayHelloAsync();
Console.WriteLine(result.Result);
}
Result.
WebOperationContext is a convenience wrapper around the OperationContext. At present, it hasn’t been implemented yet in the Aspnet Core.
https://github.com/dotnet/wcf/issues/2686
Feel free to let me know if there is anything I can help with.
I has built a self hosting WCF Service. In fact of this there is no svc-file.
The Service works well and I can call it from JavaScript with jQuery.
Now I have a look at breeze and want to call my Service with it.
I use breeze.config.initializeAdapterInstance('dataService', 'odata', true); to config Breeze and include q.min.js, datajs-1.1.3.min.js and breeze.min.js.
But what is the servicename for the EntityManager?
It's your endpoint or base address. Even if you have self hosted wcf service you must have some endpoint where self hosted service will listen.
So you must have something like this
Uri baseAddress = new Uri("http://localhost:8080/hello");
using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
{
...
}
so your breeze will be
var myServiceName = "http://localhost:8080/hello";
var em = new breeze.entityModel.EntityManager( {serviceName: myServiceName });
I am attempting to host a service that serves up basic web content (HTML, javascript, json) using a WebHttpBinding with minimal administrator involvement.
Thus far I have been successful, the only admin priviledges necessary are at install time (register the http reservation for the service account and to create the service itself). However, now I am running into issues with SSL. Ideally I would like to support a certificate outside the windows certificate store. I found this article - http://www.codeproject.com/KB/WCF/wcfcertificates.aspx - which seems to indicate you can specify the certificate on the service host, however at runtime navigating a browser to https://localhost/Dev/MyService results in a 404.
[ServiceContract]
public interface IWhoAmIService
{
[OperationContract]
[WebInvoke(
Method = "GET",
UriTemplate = "/")]
Stream WhoAmI();
}
public class WhoAmIService : IWhoAmIService
{
public Stream WhoAmI()
{
string html = "<html><head><title>Hello, world!</title></head><body><p>Hello from {0}</p></body></html>";
html = string.Format(html, WindowsIdentity.GetCurrent().Name);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return new MemoryStream(Encoding.UTF8.GetBytes(html));
}
}
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(WhoAmIService), new Uri("https://localhost:443/Dev/WhoAmI"));
host.Credentials.ServiceCertificate.Certificate = new X509Certificate2(#"D:\dev\Server.pfx", "private");
WebHttpBehavior behvior = new WebHttpBehavior();
behvior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
behvior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
behvior.AutomaticFormatSelectionEnabled = false;
WebHttpBinding secureBinding = new WebHttpBinding();
secureBinding.Security.Mode = WebHttpSecurityMode.Transport;
secureBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
ServiceEndpoint secureEndpoint = host.AddServiceEndpoint(typeof(IWhoAmIService), secureBinding, "");
secureEndpoint.Behaviors.Add(behvior);
host.Open();
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
host.Close();
}
If I change my binding security to none and the base uri to start with http, it serves up okay. This post seems to indicate that an additional command needs to be executed to register a certificate with a port with netsh (http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/6907d765-7d4c-48e8-9e29-3ac5b4b9c405/). When I try this, it fails with some obscure error (1312).
C:\Windows\system32>netsh http add sslcert ipport=0.0.0.0:443 certhash=0b740a29f
29f2cc795bf4f8730b83f303f26a6d5 appid={00112233-4455-6677-8899-AABBCCDDEEFF}
SSL Certificate add failed, Error: 1312
A specified logon session does not exist. It may already have been terminated.
How can I host this service using HTTPS without the Windows Certificate Store?
It is not possible. HTTPS is provided on OS level (http.sys kernel driver) - it is the same as providing HTTP reservation and OS level demands certificate in certificate store. You must use netsh to assign the certificate to selected port and allow accessing the private key.
The article uses certificates from files because it doesn't use HTTPS. It uses message security and message security is not possible (unless you develop your own non-interoperable) with REST services and webHttpBinding.
The only way to make this work with HTTPS is not using built-in HTTP processing dependent on http.sys = you will either have to implement whole HTTP yourselves and prepare new HTTP channel for WCF or you will have to find such implementation.
I use this simple way to attach username and password to the SOAP request header. This works fine inside Java boundaries, but I want to be able to call it with my WCF client. How do I do this?
I've tried the following code, but it does not include the credentials in the header:
wsClient.ClientCredentials.UserName.UserName = "Hello";
wsClient.ClientCredentials.UserName.Password = "World";
Thanks in advance!
That is quite awful non-standardized way. It uses custom HTTP Headers so you cannot expect that built in WCF mechanism will magically support such approach. How should WCF know that you want to add custom non-standard HTTP header to HTTP request (not SOAP header)?
Use this:
var proxy = new YourServiceClient();
using (var scope = new OperationContextScope(proxy.InnerChannel))
{
var prop = new HttpRequestMessageProperty();
prop.Headers.Add("UserName", "Hello");
prop.Headers.Add("Password", "World");
OperationContext context = OperationContext.Current;
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = prop;
proxy.CallYourOperation();
}
I want to pass Kerberos token via HTTP call to a server using WCF.
I have a piece of code that successfully does this. But it only works if I make a request to HTTPS URI.
var httpBinding = new WebHttpBinding(WebHttpSecurityMode.Transport) { MaxReceivedMessageSize = Int32.MaxValue };
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
httpBinding.Security.Transport.Realm = "MyCompany.com";
var endPoint = new EndpointAddress("https:xxxxxxxx.com/my/service); // This works
var endPoint = new EndpointAddress("http:xxxxxxxx.com/my/service); // This does not work
var channelFactory = new ChannelFactory<IMyServiceContract>(httpBinding, endPoint);
channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
_channel = channelFactory.CreateChannel();
_channel.ConsumeService();
If I make a request via the channel, and if the end point is https. It works and I can verify the Kerberos Token is in the HTTP requst.
If the service end point is HTTP, it gives error:
System.ArgumentException : The provided URI scheme 'http' is invalid; expected 'https'.
Parameter name: via
Can someone let me know how to Configure WCF so that it send Kerboros token with HTTP URI.
Regards,
Kevin
When you don't want to use HTTPS you must set your security mode to WebHttpSecurityMode.TransportCredentialOnly. If you use WebHttpSecurityMode.Transport it demands HTTPS.