首页 > 解决方案 > Spring Security 页面无法在 Chrome 上的 Iframe 中打开

问题描述

我正在使用 SpringBoot、springsecurity 和 jdk 1.8。当我尝试在 Chrome 上的 iframe 中打开任何安全的 thymleaf 页面时,它每次都会将我重定向到登录页面。它在 Firefox 和 IE 上运行良好。当我尝试在没有 iframe 的情况下打开相同的 URL 时,它工作正常。我已经给了很多时间来解决,但可以解决它。以下是我的 spring security conf 文件代码。两个域的另一件事是不同的。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers()
                .frameOptions().disable()
                .and()
                .csrf().disable()/*disbaling csrf here*/
                .authorizeRequests()
                .antMatchers("/","/login","/css/**", "/js/**", "/fonts/**","/img/**").permitAll()/*do not use spring security on this path*/
                .and()
                .formLogin()
                .successHandler(successHandler) /*after success login on web we are handling the success event*/
                .permitAll()
                .and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login/?logout") /*defining logout and login url here*/
                .permitAll()
                 /*
                 * This is for authentication failure handling
                 * */
                 http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                 /*Token based authentication we are handling here*/
                 http.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), BasicAuthenticationFilter.class);
                 http.addFilterAfter(new SameSiteFilter(), BasicAuthenticationFilter.class)
    }

谁能帮我解决这个问题?

标签: javaspring-bootspring-securitythymeleaf

解决方案


首先,我建议您不要禁用"X-Frame-Options"标头并在 iframe 中使用您的应用程序。
这会带来安全风险,您可以在此答案中了解更多信息。

现在解释你所看到的行为。
Spring Security 使用Sessioncookie 来存储用户的会话。
Cookie 与域相关联,因此,例如,如果存在与域相关联的 cookie,stackoverflow.com则该 cookie 将包含在对stackoverlow.com.

为了控制这种行为,cookie 还有一个名为SameSite.
SameSite属性可以有 3 个值,None, LaxStrict或者它可以未设置并且没有值。
当值为 时None,它的行为如上所述(包括在所有请求中)。
当值为 时Lax,cookie 将仅包含在顶级导航GET请求中。

Spring Security 使用的Sessioncookie 没有设置SameSite属性。
此时(2020 年 3 月),一些浏览器,如 Firefox 和 Edge,将 unset 属性与None.
但是,Chrome 正在尝试将 unset 属性与Lax.
您可以在Chrome 平台状态中阅读更多相关信息。

总之,在使用 Chrome 时,Sessioncookie 被视为已SameSite设置为Lax.
由于在 iframe 中呈现应用程序不是顶级导航,因此Sessioncookie 不包含在 iframe 的请求中,并且应用程序无法知道用户已登录。

您可以使用 Spring Session显式设置SameSite属性。 再次提醒您不要这样做,因为它会使您的应用程序容易受到 CSRF 和点击劫持攻击。 如果在考虑安全隐患后,您认为有必要将属性设置为,则可以通过在依赖项中包含 Spring Session 并创建自定义.None

SameSiteNoneCookieSerializer


推荐阅读