如何从单独的.NET应用程序获取当前上下文或用户标识?

Mat*_*att 5 asp.net asp.net-mvc forms-authentication membership-provider

背景

我正在开发从遗留的ASP.NET表单应用程序到MVC 4应用程序的迭代迁移.

此迁移分阶段进行,一次一个部分,因此有必要同时运行旧版和新版MVC应用程序.对于某些部分,用户将被定向到新应用程序,对于尚未迁移的部分,用户将被定向回(或保留在)旧应用程序上.

在服务器上,应用程序的结构如下:

LEGACY (.NET 2.0 forms app)--
                            |--Api (new MVC 4 WebAPI)
                            |--V2 (new MVC 4)
Run Code Online (Sandbox Code Playgroud)

所以foo对遗留页面的调用就是/foo.aspx在V2上/V2/foo.

一切都在C#中,但请注意遗留应用程序在.NET 2.0上运行,V2应用程序在.NET 4.5上运行.我不确定这是否重要,但认为重要的是要注意.

问题

我无法在应用程序之间成功共享用户/身份验证状态.显然,如果用户登录对遗留应用程序,我需要抓住他们的权威性的cookie(或采取类似行动)的V2的应用程序时,V2页面被调出,使用户不会再次提示您登录.

我试过了什么

我已经设置相同authentication,并machinekey在这两个Web.config文件中的元素:

  <authentication mode="Forms">
      <forms cookieless="UseCookies" defaultUrl="~/someUrl" loginUrl="/" path="/" protection="All" timeout="240"  enableCrossAppRedirects ="true" domain="someDomain.com" requireSSL="false"  />
  </authentication>
  <machineKey validationKey="DE78CF63226. . .788658D142AB881" decryptionKey="0B97E8BA4C4EB4B4C524. . .54E4622E14168D2D5C84461FA2" validation="SHA1" decryption="AES" />
Run Code Online (Sandbox Code Playgroud)

我在V2应用程序的Global.asax中尝试了这段代码:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (authCookie == null)
    {
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    if (authTicket == null)
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(new char[] { '|' });
    var id = new FormsIdentity(authTicket);
    var principal = new GenericPrincipal(id, roles);

    //Thread.CurrentPrincipal = principal;

    Context.User = principal;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道它是否有效,因为遗留应用程序与我的V2应用程序不在同一个解决方案中,因此当我调试V2应用程序时,我没有办法通过Legacy应用程序登录并模拟在legacy和V2之间跳跃的实际用户体验.

我也试过把它添加到我HomeController的希望,相同的机器键对我来说会有些神奇:

 ViewBag.UserName = User.Identity.Name;
Run Code Online (Sandbox Code Playgroud)

显然,我然后绑定ViewBag.UserName到视图中的html元素,但这似乎也不起作用.

小智 2

在父应用程序上设置 machineKey CompatibilityMode="Framework20SP2"。

.net 4.5 无法读取 4.0(或更低版本)的身份验证令牌

http://technet.microsoft.com/en-us/subscriptions/index/system.web.configuration.machinekeycompatibilitymode

http://blogs.msdn.com/b/webdev/archive/2012/10/23/cryptographic-improvements-in-asp-net-4-5-pt-2.aspx