【问题标题】:Share cookie .net Core 3 and Asp.net共享 cookie .net Core 3 和 Asp.net
【发布时间】:2020-08-28 20:15:17
【问题描述】:

尝试按照此处的 microsoft 文档共享身份验证 cookie:MS Docs

这是来自旧 Webforms 项目的我的 Startup.vb。

  <Assembly: OwinStartup("Me", GetType(Startup))>
    Public Class Startup
       Public Sub Configuration(ByVal app As IAppBuilder)

        Dim opt = New CookieAuthenticationOptions
        opt.AuthenticationType = "Identity.Application"
        opt.CookieName = ".SSO"
        opt.LoginPath = New PathString("/Login.aspx")
        opt.CookieDomain = "localhost"
        opt.CookieHttpOnly = False
        opt.CookieSecure = CookieSecureOption.SameAsRequest
        Dim proc = DataProtectionProvider.Create(New DirectoryInfo("c:\Temp\DataKeys"), Function(s) s.SetApplicationName("MyApp")).CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2")
        Dim shim = New DataProtectorShim(proc)

        opt.CookieManager = New ChunkingCookieManager()
        opt.TicketDataFormat = New AspNetTicketDataFormat(shim)
        app.UseCookieAuthentication(opt)

    End Sub

End Class

这是 .net core 3 应用程序的启动。

 public class Startup
{
    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        Configuration = configuration;
        Environment = env;
    }
    public IWebHostEnvironment Environment { get; }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor().AddHubOptions(o =>
        {
            o.MaximumReceiveMessageSize = 2000 * 1024 * 1024; // 10MB
        });
        services.AddSingleton<IConfiguration>(Configuration);

        services.AddSingleton<IJwtHandler, JwtHandler>();
        services.Configure<TokenSettings>(Configuration.GetSection("Token"));
        services.AddSingleton<IWebHostEnvironment>(Environment);

        services.AddHttpContextAccessor();
        services.AddScoped<HttpContextAccessor>();
        services.AddFileReaderService();

        services.AddTelerikBlazor();
        services.AddSweetAlert2();


        services.AddSingleton<WeatherForecastService>();

        services.Configure<AnimateOptions>(options =>
        {
            options.Animation = Animations.Fade;
            options.Duration = TimeSpan.FromMilliseconds(200);
        });


        services.AddDataProtection()
            .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"C:\Temp\DataKeys"))
            .SetApplicationName("MyApp");

        services.AddAuthentication("Identity.Application")
        .AddCookie("Identity.Application", options =>
        {
            options.Cookie = new CookieBuilder
            {
                Domain = "localhost",
                Name = ".SSO",
                SameSite = SameSiteMode.Lax,
                HttpOnly= false,
                SecurePolicy = CookieSecurePolicy.SameAsRequest,
                IsEssential = true
            };
        });


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {



        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();


        app.UseRouting();

        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
}

我登录到旧版 Webforms 应用程序,一切正常。我尝试导航到 .net core 3 应用程序,它说我没有通过身份验证,它确实通过了 cookie。我不确定我做错了什么?

【问题讨论】:

  • 显示你的startup classConfigureServices 方法
  • 你最终弄明白了吗?我也有同样的情况。

标签: c# asp.net asp.net-core .net-core blazor


【解决方案1】:

我确实最终解决了大部分问题。

在 .net Core 3 应用程序中,如果您计划从 .net 核心应用程序生成密钥,则可以删除“DisableAutomaticKeyGeneration()”调用。

     var proc = DataProtectionProvider.Create(new DirectoryInfo(Configuration["SSO:KeyLocation"].ToString()), (builder) => { builder.SetApplicationName("MyApp").ProtectKeysWithDpapi().DisableAutomaticKeyGeneration(); })
        .CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2");

            services.AddAuthentication("Identity.Application")
            .AddCookie("Identity.Application", options =>
            {
                options.TicketDataFormat = new TicketDataFormat(proc);
                options.SlidingExpiration = true;
                options.Cookie = new CookieBuilder
                {
                    Domain = Configuration["SSO:Domain"].ToString(),
                    Name = ".SSO",
                    SecurePolicy = CookieSecurePolicy.None,
                    IsEssential = true,
                };

            });

在 .Net Framework 应用程序上,如果 Web 应用程序未在应用程序池的同一服务帐户下运行,您可以删除“ProtectKeysWithDpapi()”。

此外,您需要确保在两个应用程序上都安装了此版本的 nuget 包, Microsoft.AspNetCore.DataProtection v3.1.3

Dim opt = New CookieAuthenticationOptions
opt.AuthenticationType = "Identity.Application"
opt.CookieName = ".SSO"
opt.LoginPath = New PathString("/Login.aspx")
opt.CookieDomain = ConfigurationManager.AppSettings("SSODomain")
opt.SlidingExpiration = True

Dim proc = DataProtectionProvider.Create(New DirectoryInfo(ConfigurationManager.AppSettings("SSOKeyLocation")), Function(s) s.SetApplicationName("MyApp").SetDefaultKeyLifetime(TimeSpan.FromDays(9000)).ProtectKeysWithDpapi()).CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2")

Dim shim = New DataProtectorShim(proc)

opt.TicketDataFormat = New AspNetTicketDataFormat(shim)

app.UseCookieAuthentication(opt)

对于本地主机开发/测试,只需将域设置为“本地主机”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-02
    • 2020-05-18
    • 2018-12-20
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2019-07-05
    • 2018-02-17
    相关资源
    最近更新 更多