简体   繁体   English

在 ASP.NET Core 2.2 和 ASP 之间共享 Cookie 身份验证。 NET MVC 5 (.NET Framework 4.6.1) 没有 Microsoft.Identity

[英]Share Cookie authentication between ASP.NET Core 2.2 and ASP. NET MVC 5 (.NET Framework 4.6.1) without Microsoft.Identity

I have two application, the old one written in ASP.NET MVC5 and the new one written in ASP.NET Core 2.2.我有两个应用程序,一个是用 ASP.NET MVC5 编写的旧应用程序,另一个是用 ASP.NET Core 2.2 编写的新应用程序。 I want to share the cookie created in the ASP.NET Core application to the ASP.NET MVC5.我想将在 ASP.NET Core 应用程序中创建的 cookie 共享给 ASP.NET MVC5。 I tried what is explained in this article https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-2.2 but seems that my ASP.NET MVC5 doesn't find the cookie.我尝试了本文https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-2.2 中解释的内容,但似乎我的 ASP.NET MVC5 没有找到曲奇饼。 (Maybe because I'm not using Microsoft.Identity for the users?) The cookie is created in ASP.NET Core with this configuration (Startup.cs): (也许是因为我没有为用户使用 Microsoft.Identity?)cookie 是在 ASP.NET Core 中使用以下配置(Startup.cs)创建的:

public void ConfigureServices(IServiceCollection services)
    {
      // Cookie
      services.Configure<CookiePolicyOptions>(options =>
      {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
      }); 



services.AddDataProtection()
      .PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp\shared-auth-ticket-keys\"))
      .SetApplicationName(CookieConst.SHARED_APP_NAME);

  services
    .AddAuthentication(CookieConst.AUTHENTICATION_TYPE)
    .AddCookie(CookieConst.AUTHENTICATION_TYPE, options =>
    {
      options.Cookie.HttpOnly = false;
      options.LoginPath = new PathString("/login");
      options.LogoutPath = new PathString("/login");
      options.AccessDeniedPath = new PathString("/login");
      options.Cookie.HttpOnly = false;
      options.Cookie.SameSite = SameSiteMode.None;
      options.Cookie.Name = CookieConst.AUTHENTICATION_SCHEME;
      options.Cookie.Path = "/";
      options.Cookie.Domain = "localhost";
      options.DataProtectionProvider = DataProtectionProvider.Create(
        new DirectoryInfo(@"c:\temp\shared-auth-ticket-keys\"),
        (builder) => { builder.SetApplicationName(CookieConst.SHARED_APP_NAME); }).CreateProtector(
                  "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                  CookieConst.AUTHENTICATION_TYPE,
                  "v2");
    });

   …

}

The cookie is created with this code called by login: cookie 是使用以下代码创建的,由 login 调用:

public void Validate()
{
  AuthenticationProperties authenticationProperties;
  ClaimsPrincipal principal;
  string cultureName;

  var expireTime = DateTimeHelper.GetNowDate().AddMinutes(CookieConst.EXPIRE_TIME_IN_MINUTES);

  authenticationProperties = new AuthenticationProperties()
  {
    AllowRefresh = true,
    IsPersistent = true,
    ExpiresUtc = expireTime
  };

  // Add Authentication Cookie
  var claims = new List<Claim>
      {
        new Claim(ClaimTypes.Name, "test"),
        new Claim(BeanClaimTypes.User, "-1"),
        new Claim(BeanClaimTypes.Company, "-1"),
        new Claim(BeanClaimTypes.Roles, "testRole"),
        new Claim(BeanClaimTypes.Permissions, "testPermission"),
        new Claim(BeanClaimTypes.Culture, "en-US")
      };
  var identity = new ClaimsIdentity(claims, CookieConst.AUTHENTICATION_TYPE);
  principal = new ClaimsPrincipal(identity);

  HttpContext.SignInAsync(CookieConst.AUTHENTICATION_TYPE, principal, authenticationProperties);
}

In the ASP.NET MVC5 application this is the configuration (Startup.Auth.cs):在 ASP.NET MVC5 应用程序中,这是配置 (Startup.Auth.cs):

  public void ConfigureAuth(IAppBuilder app)
    {
      //// Configure the db context, user manager and signin manager to use a single instance per request
      //app.CreatePerOwinContext(ApplicationDbContext.Create);
      //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
      //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);  

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
      AuthenticationType = CookieConst.AUTHENTICATION_TYPE,
      CookieName = CookieConst.AUTHENTICATION_SCHEME,
      LoginPath = new PathString("/Account/Login"),
      Provider = new CookieAuthenticationProvider
      {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                      validateInterval: TimeSpan.FromMinutes(30),
                      regenerateIdentity: (manager, user) =>
                          user.GenerateUserIdentityAsync(manager))
      },
      TicketDataFormat = new AspNetTicketDataFormat(
          new DataProtectorShim(
              DataProtectionProvider.Create(new DirectoryInfo(@"c:\temp\shared-auth-ticket-keys\"),
                  (builder) => { builder.SetApplicationName(CookieConst.SHARED_APP_NAME); })
              .CreateProtector(
                  "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                  CookieConst.AUTHENTICATION_TYPE,
                  "v2"))),
    CookieManager = new ChunkingCookieManager()
  });

  app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

  System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
}

I don't understand the commented part and Provider property of CookieAuthenticationOptions, because I'm not using Microsoft.Identity and I don't know how to read the cookie and “parse” it to have the ASP.NET MVC5 principal filled.我不明白 CookieAuthenticationOptions 的注释部分和 Provider 属性,因为我没有使用 Microsoft.Identity,我不知道如何读取 cookie 并“解析”它以填充 ASP.NET MVC5 主体。

What am I doing wrong?我究竟做错了什么? Thanks谢谢

  options.Cookie.Domain = "localhost";

为本地主机删除这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.Net Core 2.2身份验证 - Asp.Net Core 2.2 Identity Authentication ASP.NET MVC中的身份cookie身份验证 - Identity cookie authentication in ASP.NET MVC 没有身份验证Asp.net核心的Cookie - Cookie without Identity Asp.net core ASP。 带有 cookie 身份验证的 Net Core 2.2:当未授权 API 仅控制器时如何避免页面重定向 - ASP. Net Core 2.2 with cookie authentication: how to avoid page redirect when not authorized for API only controllers 在没有实体框架和迁移的ASP.NET Core MVC应用程序中使用ASP.NET标识 - Using ASP.NET Identity in an ASP.NET Core MVC application without Entity Framework and Migrations 共享 cookie .net Core 3 和 Asp.net - Share cookie .net Core 3 and Asp.net 如何使用Asp.Net.Identity和Entity Framework 6在Asp.Net Core 2.0 Target Framework 4.6.1中设置身份? - How can I setup identity in Asp.Net Core 2.0 Target Framework 4.6.1 using Asp.Net.Identity and Entity Framework 6? 结合使用Microsoft Bot Framework和ASP.NET Core 2.2 - Using Microsoft Bot Framework with ASP.NET Core 2.2 使用 ASP.NET Core 2.1 / 3+ 身份验证身份验证 cookie - Validate authentication cookie with ASP.NET Core 2.1 / 3+ Identity 页面上的Cookie身份验证问题请求ASP.NET Core和身份 - Cookie authentication issues on page request ASP.NET Core & Identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM