Created
May 30, 2013 13:58
-
-
Save anonymous/5678026 to your computer and use it in GitHub Desktop.
Sample WCF service that services content over HTTP and authenticates with NTLM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.ServiceModel; | |
using System.ServiceModel.Description; | |
using System.ServiceModel.Web; | |
using System.Text; | |
namespace WindowsAuthService | |
{ | |
[ServiceContract] | |
public interface ITestService | |
{ | |
[OperationContract] | |
[WebGet(UriTemplate = "{*path}")] | |
Stream Get(string path); | |
} | |
public class TestService : ITestService | |
{ | |
public Stream Get(string path) | |
{ | |
WebOperationContext.Current.OutgoingResponse.Headers.Add(HttpResponseHeader.ContentType, "text/plain"); | |
if (OperationContext.Current.ServiceSecurityContext == null) | |
return new MemoryStream(Encoding.ASCII.GetBytes(String.Format("Hello, {0}!", "Anonymous Stranger"))); | |
else | |
return new MemoryStream(Encoding.ASCII.GetBytes(String.Format("Hello, {0}!", OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name))); | |
} | |
} | |
class Program | |
{ | |
private const string URL = "http://e278-jsc.eni.local:7777"; | |
static void Main(string[] args) | |
{ | |
WebServiceHost serviceHost = new WebServiceHost(new TestService()); | |
foreach (IServiceBehavior attr in serviceHost.Description.Behaviors) | |
{ | |
if (attr is ServiceBehaviorAttribute) | |
{ | |
ServiceBehaviorAttribute serviceAttr = (ServiceBehaviorAttribute)attr; | |
serviceAttr.InstanceContextMode = InstanceContextMode.Single; | |
serviceAttr.ConcurrencyMode = ConcurrencyMode.Multiple; | |
} | |
} | |
WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly); | |
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; | |
ServiceEndpoint serviceEndpoint = serviceHost.AddServiceEndpoint(typeof (ITestService), binding, URL); | |
serviceEndpoint.Behaviors.Add(new WebHttpBehavior()); | |
Console.WriteLine("Service Listening @ " + URL); | |
serviceHost.Open(); | |
Console.WriteLine("[ Press Enter to Quit ]"); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment