Search code examples
asp.net-mvc-3wcfweb-servicesrestwindows-authentication

Get Username of Currently interacting User in WCF both Rest Endpoint and MVC3 with Windows Authentication


In an MVC3 project that I'm working on we're trying to move a lot of our logic that is currently in the controllers into a service layer and expose it as a REST Service in WCF.

So in our Global.asax we create a Service Route like so:

RouteTable.Routes.Add(new ServiceRoute
    ("Exampleservice", new WebServiceHostFactory(), typeof(ExampleService)));

and our controllers access the service something like this:

public class ExampleController : Controller {
    private IExampleService service;

    public ExampleController() {
        this.service = new ExampleService();
    } 

    public ActionResult Index() {
         var results = service.GetAll();
         return View(results);
    }
}

The main point here being that we use the service class directly (without making requests over the network with an HttpClient).

Our website uses Windows Authentication (it's an intranet site) and we would like to keep it that way. My Question is, is there a way that I can get the User's Identity in the service class that will work both for how we have the Controllers using the service, and the way that WCF uses the service?

For example:

[ServiceContract]
public interface IExampleService
{
    [WebGet(UriTemplate = "/")]
    List<Results> GetAll();
}

public class ExampleService : IExampleService
{
     List<Results> GetAll() {
         // Get User Name Here
         // In ASP.Net I would use User.Identity.Name
         // If I was just worrying about the the REST service I would use
         // ServiceSecurityContext.Current.WindowsIdentity.Name
     }
}

Solution

  • The instruction suggested by @Ryand.Johnson is correct. The point here is that the controller do not send any credentials to the web service because it run under the asp.net user indentity not the identity of the currently loggedd user. The only way to pass the identity to the proxy is by embedding the call to the web service within an impersonation context this way:

    using (WindowsImpersonationContext impersonatedUser = (User.Identity as System.Security.Principal.WindowsIdentity).Impersonate()){ 
         //your proxy call here  }
    

    If still this way you get null you have to set manually the default credentials to your proxy