【问题标题】:Using ASP.NET 4 cookie in Web API edit: Core 2.0在 Web API 编辑中使用 ASP.NET 4 cookie:Core 2.0
【发布时间】:2017-08-30 16:14:59
【问题描述】:

我正在向旧版 ASP.NET 4 应用程序添加 Angular 应用程序和 Web API(编辑:Core 2.0)。旧版应用程序使用表单身份验证,我无法更改它。我希望 Web API 检测到用户已登录并设置声明等(或替代方法)以授权后续 Web API 请求。

我尝试读取 Web API 中的身份验证 cookie,但无法解密它,我相信是因为 ASP.NET Core 2.0 不理解 ASP.NET 4 cookie 加密。我已经尝试过机器密钥等的网络配置设置,但没有成功。我在这里有什么选择?

【问题讨论】:

    标签: asp.net-web-api asp.net-core


    【解决方案1】:

    配置您的 ASP.NET 网站:

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

    那么你的 Core 2 应用程序,它们应该使用相同的文件夹来共享身份验证票证和相同的身份验证方法:

     public void ConfigureServices(IServiceCollection services)
     {
         services.AddCookieAuthentication(options => { 
            options.AuthenticationScheme = "Cookie",
            options.LoginPath = "/Account/Login";
            options.CookieName = ".AspNet.SharedCookie";
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;
            options.TicketDataFormat = ew AspNetTicketDataFormat(
           new DataProtectorShim(
               DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"))
               .CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
               "Cookies", "v2")))
         });
     }
    
     public void Configure(IApplicationBuilder app)
     {
         app.UseAuthentication();
     }
    

    文档:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x

    【讨论】:

    • 如链接中所述,这适用于 Core 1 和 ASP.NET 4.5,与相关堆栈不兼容。
    • 谢谢伊斯玛。您是说这将允许 Core 2 理解在 ASP.NET 4 中创建的 cookie?你有这样的工作吗?
    • 嘿,我忘记了票数据格式,我再次编辑了答案。我自己还没有测试过,但它应该可以工作,或者至少让你朝着正确的方向前进;)
    • 感谢 Isma,但我无法更改现有的身份验证。
    • 然后试试 asp.net 核心部分,但如果你不能共享身份验证票,我认为这是不可能的......
    猜你喜欢
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多