asp.net-mvc-3 - 使用 Windows 身份验证获取 WCF 中当前交互用户的用户名,包括 Rest Endpoint 和 MVC3

标签 asp.net-mvc-3 wcf web-services rest windows-authentication

在我正在处理的 MVC3 项目中,我们试图将当前在 Controller 中的许多逻辑移动到服务层中,并将其作为 WCF 中的 REST 服务公开。

所以在我们的 Global.asax 中,我们创建了一个服务路由,如下所示:

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

和我们的 Controller 访问服务是这样的:
public class ExampleController : Controller {
    private IExampleService service;

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

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

这里的要点是我们直接使用服务类(不使用 HttpClient 通过网络发出请求)。

我们的网站使用 Windows 身份验证(它是一个 Intranet 站点),我们希望保持这种方式。我的问题是,有没有一种方法可以让我在服务类中获取用户的身份,它既适用于我们让 Controller 使用服务的方式,也适用于 WCF 使用服务的方式?

例如:
[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
     }
}

最佳答案

@Ryand.Johnson 建议的指令是正确的。这里的要点是 Controller 不会向 Web 服务发送任何凭据,因为它在 asp.net 用户身份下运行,而不是当前登录用户的身份。将身份传递给代理的唯一方法是通过以下方式在模拟上下文中嵌入对 Web 服务的调用:

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

如果仍然以这种方式获得 null,则必须手动设置代理的默认凭据

关于asp.net-mvc-3 - 使用 Windows 身份验证获取 WCF 中当前交互用户的用户名,包括 Rest Endpoint 和 MVC3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10921253/

相关文章:

php - 使用 PHP 调用 WCF 服务(具有联合安全性)

WCF 跟踪 (svclog) 间歇性停止。回收AppPool后启动

c# - 创建 Web 服务 C# ASP.Net

c# - 无法在 MonoDevelop 中打开 ASP.NET MVC 3 解决方案的测试项目

javascript - 使用 MVC3 RAZOR View 引擎执行 JavaScript?

asp.net-mvc - Razor:如何强制文件夹中的 View ,从特殊类继承

java - Web 服务读取超时,但操作仍然完成?

c# - mvc 3 Html.EditorFor 添加 html 属性不起作用

wcf - Silverlight 不喜欢我的 WCF MessageContract。为什么?

c# - 如何仅允许特定用户访问 IIS 上托管的 WCF Web 服务?