在 OWIN 中共享旧版 FormsAuthentication cookie

Sharing legacy FormsAuthentication cookie in OWIN

我们已将两个 ASP.NET MVC4 网络应用程序升级到 MVC5,为了使用 SignalR 2.x,我们必须在更新后的应用程序中使用 OWIN。 这两个应用程序在 web.config 中共享相同的 machinekeyauthentication 部分,如果用户在应用程序 1 中登录,他们也会在应用程序 2 中自动登录:

<machineKey validationKey="<themachinekey>" decryptionKey="<thedecryptionKey>" validation="SHA1" decryption="AES" />
<authentication mode="Forms">
  <forms timeout="2880" name=".ASPAUTH_VOCC" path="/" />
</authentication>

对用户进行身份验证后,两个应用程序都会以相同的方式直接创建身份验证ticket/cookie:

string userData = "ApplicationSpecific data for this user.";

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
    userName,
    DateTime.Now,
    DateTime.Now.AddMinutes(2880),
    persistent,
    userData,
    FormsAuthentication.FormsCookiePath);

// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
if (persistent)
{
    cookie.Expires = DateTime.Now.AddMinutes(2880);
}

// Create the cookie.
HttpContext.Current.Response.Cookies.Add(cookie);

我还要提一下,在更新过程中,我没有在启动时使用app.UseCookieAuthentication方法,而是更喜欢坚持使用上面的代码进行身份验证。

虽然此方法在 MVC4 上运行良好,但在更新后,两个 Web 应用程序的行为就好像来自另一个应用程序的身份验证 cookie 无效一样,虽然用户在一个应用程序中已通过身份验证,但在另一个应用程序中仍未通过身份验证应用程序。

web.configsystem.web 中添加以下行解决了问题:

<httpRuntime targetFramework="4.5" />

不确定与 v4.0 相比,.NET 4.5 中的 FormsAuthentication encryption/decryption 方法发生了什么变化。添加上述内容后,用户在两个应用程序中都按预期进行了身份验证。