在ASP.NET Core 2.2和ASP之间共享Cookie身份验证。没有Microsoft.Identity的NET MVC 5(.NET Framework 4.6.1) [英] Share Cookie authentication between ASP.NET Core 2.2 and ASP. NET MVC 5 (.NET Framework 4.6.1) without Microsoft.Identity

查看:81
本文介绍了在ASP.NET Core 2.2和ASP之间共享Cookie身份验证。没有Microsoft.Identity的NET MVC 5(.NET Framework 4.6.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序,一个是用ASP.NET MVC5编写的旧应用程序,另一个是用ASP.NET Core 2.2编写的新应用程序。我想将在ASP.NET Core应用程序中创建的cookie共享给ASP.NET MVC5。
我尝试了本文 https://docs.microsoft.com/zh-cn/aspnet/core/security/cookie-sharing?view=aspnetcore-2.2 ,但我的ASP.NET MVC5似乎找不到曲奇饼。 (也许是因为我没有为用户使用Microsoft.Identity?)
使用以下配置(Startup.cs)在ASP.NET Core中创建cookie:

I have two application, the old one written in ASP.NET MVC5 and the new one written in ASP.NET Core 2.2. I want to share the cookie created in the ASP.NET Core application to the 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. (Maybe because I’m not using Microsoft.Identity for the users?) The cookie is created in ASP.NET Core with this configuration (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");
    });

   …

}

cookie是使用以下通过登录调用的代码创建的:

The cookie is created with this code called by 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);
}

在ASP.NET MVC5应用程序中,此配置为(Startup.Auth。 cs):

In the ASP.NET MVC5 application this is the configuration (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";
}

我不了解CookieAuthenticationOptions的注释部分和Provider属性,因为我我没有使用Microsoft。Identity,而且我不知道如何读取Cookie并解析它以填充ASP.NET MVC5主体。

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.

什么是我做错了吗?
谢谢

What am I doing wrong? Thanks

推荐答案

  options.Cookie.Domain = "localhost";

为此本地主机删除此

delete this this for local host

这篇关于在ASP.NET Core 2.2和ASP之间共享Cookie身份验证。没有Microsoft.Identity的NET MVC 5(.NET Framework 4.6.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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