asp.net - 在表单例份验证中使用 ASP.Net Identity 2 cookie

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

我在虚拟目录中设置了一个 Owin Identity 应用程序和另一个应用程序。虚拟应用程序使用传统表单例份验证设置,两个 Web.config 具有相同的 <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?

最佳答案

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/

太大了,这里就不解释了。

关于asp.net - 在表单例份验证中使用 ASP.Net Identity 2 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27082598/

相关文章:

c# - ASP.NET MVC ApplicationDbContext 创建

c# - 使用 JSON.NET 将 C# 对象转换为 JSON 时出现额外的 '\'

c# - 使用手动创建的表单例份验证票设置超时

asp.net - 启用 Application Insights 会使 Web 应用程序挂起

asp.net - 表单例份验证未正确验证用户

asp.net-mvc-2 - 允许匿名访问内容和脚本文件夹

asp.net-identity - asp.net身份.GenerateUserToken()有什么用

asp.net-core - 为什么 Visual Studio 2019 16.9.5 中 .NET Core 3.1 和 .NET 5 的 Scaffolding Identity 失败?

asp.net - 将含有特殊字符的字符串插入RTF

asp.net - 使用 Azure 表存储进行 ASP.NET session