【问题标题】:ASP.NET core iframe authentication cookieASP.NET 核心 iframe 身份验证 cookie
【发布时间】:2021-06-26 23:39:31
【问题描述】:

我的 iframe 出现问题。每当我尝试登录时,我的身份验证 cookie 似乎都不起作用,因为我只是被重定向回我的登录屏幕。我该如何解决这个问题?

当我只是正常运行网站时,cookie 工作正常,但一旦我在 iframe 中显示它,一切都会变糟。

这是我的 Startup.cs:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
          
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddMvc().AddRazorPagesOptions(o =>
            {
                o.Conventions.ConfigureFilter(new Microsoft.AspNetCore.Mvc.IgnoreAntiforgeryTokenAttribute());
                
            });

            // Here we set some settings for the authentication cookie, with the class CookieAuthenticationOptions which is a part of the Microsoft.AspNetCore.Authentication.Cookies namespace.
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                // Here we set the name of the authentication cookie.
                options.Cookie.Name = "AuthCookie";
                // Here we set the cookie to Http Only, because no scripts should have access to change the cookie.
                options.Cookie.HttpOnly = true;
                // Here we set the cookie to be only send over an HTTPS connection.
                options.Cookie.SecurePolicy = CookieSecurePolicy.None;
                // Here we set the SameSite to lax, because not all browser's set cookies without a SameSite value to lax.
                options.Cookie.SameSite = SameSiteMode.Lax;
                // Here we set the path to the Access denied site to our AccessDenied site. The site is shown if a user don't have access to the site he/she/it is trying to visit.
                options.AccessDeniedPath = "/";
                // Here we set the login page. The user is redirected to this site if he/she/it is not logged in and the site require the user to be logged in.
                options.LoginPath = "/";
                // Here we set the log out site.
                options.LogoutPath = "/Logout";
            });

        }

        




        // 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.Use(async (context, next) =>
             {
                 //
                 //context.Response.Headers.Remove("X-Frame-Options");
                 context.Response.Headers.Add("X-Frame-Options", "DENY");
             });*/

            app.Use(async (context, next) =>
            {
                context.Response.Headers.Remove("X-Frame-Options");
                context.Response.Headers.Add("X-Frame-Options", "ALLOWALL");
                //context.Response.Headers.Add("Content-Security-Policy", "frame-ancestors https://kasp151f.000webhostapp.com/");
                await next();
            });

            // app.UseHttpsRedirection();
            // Here I enable authentication capeabilities for the website.
            app.UseAuthentication();
            // Here I enable authorization capeabilities for the website.
            app.UseAuthorization();
            app.UseStaticFiles();

            app.UseRouting();
            
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

    }

这是我的 iframe:

<iframe width="1280" height="720" frameBorder="0"  scrolling="no"  onload="HandleLocationChange(this, this.contentWindow.location.href)" src="http://kasperssejeside.tk/"></iframe>

【问题讨论】:

  • 您的意思是使用 iframe 标签在另一个应用程序中呈现您的网站吗?尝试使用F12开发者工具检查cookie是否存在,确保没有过期,然后尝试清除cookie重新检查是否有效?
  • 我检查了 cookie 并且 cookie 存在,但它就像参数没有设置在其中

标签: html asp.net-core iframe razor-pages x-frame-options


【解决方案1】:

正如 Halvor 所建议的,这确实是 SameSite cookie 问题。本文描述了一个修复:Upcoming SameSite Cookie Changes in ASP.NET and ASP.NET Core

总结:您需要将SameSite 选项设置为none 以允许使用cookie,尽管iframe。问题:对于没有此选项的浏览器,它将中断。对于这些,您需要忽略该选项。

asp.net core 的实现(取自上述文章,稍作改动): 所有更改都在Startup.cs 中。 将此添加到ConfigureServices(...) 的正文中:

services.Configure<CookiePolicyOptions>(options =>
{
    options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
    options.OnAppendCookie = cookieContext =>
        cookieContext.CookieOptions.SameSite = DisallowsSameSiteNone(cookieContext.Context) ? SameSiteMode.Unspecified : SameSiteMode.None;  
    options.OnDeleteCookie = cookieContext =>
        cookieContext.CookieOptions.SameSite = DisallowsSameSiteNone(cookieContext.Context) ? SameSiteMode.Unspecified : SameSiteMode.None;
    options.Secure = CookieSecurePolicy.Always; // required for chromium-based browsers

});

将此添加到 Configure(...) 的正文中 app.UseAuthentication() 之前

app.UseCookiePolicy();

并添加此方法

private static bool DisallowsSameSiteNone(HttpContext httpContext)
{
    var userAgent = httpContext.Request.Headers["User-Agent"].ToString();

    if (string.IsNullOrEmpty(userAgent))
    {
        return false;
    }

    // Cover all iOS based browsers here. This includes:
    // - Safari on iOS 12 for iPhone, iPod Touch, iPad
    // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
    // - Chrome on iOS 12 for iPhone, iPod Touch, iPad
    // All of which are broken by SameSite=None, because they use the iOS networking stack
    if (userAgent.Contains("CPU iPhone OS 12") || userAgent.Contains("iPad; CPU OS 12"))
    {
        return true;
    }

    // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:
    // - Safari on Mac OS X.
    // This does not include:
    // - Chrome on Mac OS X
    // Because they do not use the Mac OS networking stack.
    if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") &&
        userAgent.Contains("Version/") && userAgent.Contains("Safari"))
    {
        return true;
    }

    // Cover Chrome 50-69, because some versions are broken by SameSite=None, 
    // and none in this range require it.
    // Note: this covers some pre-Chromium Edge versions, 
    // but pre-Chromium Edge does not require SameSite=None.
    if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
    {
        return true;
    }

    return false;
}

【讨论】:

    【解决方案2】:

    听起来更像是 SameSite cookie 问题。要对此进行测试,请尝试在 Chrome 中禁用 SameSite 设置,chrome://flags/#same-site-by-default-cookies,或检查它是否适用于 IE。

    如果这解决了您的问题,您将需要修改一个或多个 cookie 上的 SameSite 标志。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 2021-11-07
      • 2019-08-05
      • 2017-05-13
      • 1970-01-01
      • 2011-08-19
      • 2020-06-03
      • 1970-01-01
      相关资源
      最近更新 更多