在表单身份验证中使用ASP.Net Identity 2 cookie

时间:2014-11-22 21:10:05

标签: asp.net forms-authentication asp.net-identity owin

我有一个Owin Identity应用程序和另一个在虚拟目录中设置的应用程序。虚拟应用程序使用传统的表单身份验证进行设置,并且两个Web.configs都具有相同的<machineKey>集。我可以使用Identity应用程序登录,并可以看到生成的cookie。但是,当我尝试访问虚拟应用程序时,它表示我未经过身份验证。

在Identity应用程序中,我有以下设置:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
  AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
  LoginPath = new PathString("/login.aspx"),
  Provider = new CookieAuthenticationProvider
  {
    // Enables the application to validate the security stamp when the user logs in.
    // This is a security feature which is used when you change a password or add an external login to your account.  
    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
      validateInterval: TimeSpan.FromMinutes(30),
      regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
  }
});

在虚拟应用中,我的授权设置如下:

<authorization>
      <deny users="?" />
</authorization>

是否有任何指针让虚拟应用程序识别Identity设置的cookie?

1 个答案:

答案 0 :(得分:12)

Cookie包含身份验证票证。对于cookie身份验证中间件与表单身份验证,此故障单的格式不同。无法使FAM读取cookie身份验证中间件创建的cookie。也就是说,您可以编写自己的HTTP模块,类似于FAM来读取cookie身份验证中间件创建的cookie,就像这样。

public class MyHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += OnApplicationAuthenticateRequest;
    }
    private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
    {
        var request = HttpContext.Current.Request;
        var cookie = request.Cookies.Get(".AspNet.ApplicationCookie");
        var ticket = cookie.Value;
        ticket = ticket.Replace('-', '+').Replace('_', '/');

        var padding = 3 - ((ticket.Length + 3) % 4);
        if (padding != 0)
            ticket = ticket + new string('=', padding);

        var bytes = Convert.FromBase64String(ticket);

        bytes = System.Web.Security.MachineKey.Unprotect(bytes,
            "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
                "ApplicationCookie", "v1");

        using (var memory = new MemoryStream(bytes))
        {
            using (var compression = new GZipStream(memory, 
                                                CompressionMode.Decompress))
            {
                using (var reader = new BinaryReader(compression))
                {
                    reader.ReadInt32();
                    string authenticationType = reader.ReadString();
                    reader.ReadString();
                    reader.ReadString();

                    int count = reader.ReadInt32();

                    var claims = new Claim[count];
                    for (int index = 0; index != count; ++index)
                    {
                        string type = reader.ReadString();
                        type = type == "\0" ? ClaimTypes.Name : type;

                        string value = reader.ReadString();

                        string valueType = reader.ReadString();
                        valueType = valueType == "\0" ? 
                                       "http://www.w3.org/2001/XMLSchema#string" : 
                                         valueType;

                        string issuer = reader.ReadString();
                        issuer = issuer == "\0" ? "LOCAL AUTHORITY" : issuer;

                        string originalIssuer = reader.ReadString();
                        originalIssuer = originalIssuer == "\0" ? 
                                                     issuer : originalIssuer;

                        claims[index] = new Claim(type, value, 
                                               valueType, issuer, originalIssuer);
                    }

                    var identity = new ClaimsIdentity(claims, authenticationType, 
                                                  ClaimTypes.Name, ClaimTypes.Role);

                    var principal = new ClaimsPrincipal(identity);

                    System.Threading.Thread.CurrentPrincipal = principal;
                    HttpContext.Current.User = principal;
                }
            }
        }
    }


    public void Dispose() { }
}

有关我在此处所做的解释,请转到我的博客条目。

http://lbadri.wordpress.com/2014/11/23/reading-katana-cookie-authentication-middlewares-cookie-from-formsauthenticationmodule/

这里解释得太大了。