在表单身份验证中使用ASP.Net Identity 2 Cookie [英] Using ASP.Net Identity 2 cookie in forms authentication

查看:130
本文介绍了在表单身份验证中使用ASP.Net Identity 2 Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Owin Identity application and another application set up in a virtual directory. The virtual app is set up using traditional forms authentication, and both Web.configs have the same <machineKey> set. I can login using the Identity app, and can see the resulting cookie. However, when I try to access the virtual app it says I am not authenticated.

在身份"应用中,我具有以下设置:

In the Identity app, I have the following setup:

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))
  }
});

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

And in the virtual app, I have authorization set up as follows:

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

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

Any pointers to get the virtual app to recognize the cookie set by Identity?

推荐答案

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

The cookie contains authentication ticket. The format of this ticket is different for cookie authentication middleware vs forms authentication. It is not possible to make FAM read the cookie created by the cookie authentication middleware. That said, you can write your own HTTP module, similar to FAM to read the cookie created by the cookie authentication middleware, like this.

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() { }
}

有关我在这里所做的解释,请转到我的博客条目.

For the explanation of what I do here, please go to my blog entry.

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

太大了,在这里无法解释.

It is too big to explain here.

这篇关于在表单身份验证中使用ASP.Net Identity 2 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆