我正在使用 Spring Boot、Spring Security 和 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)
}
我该如何修复它?
首先,我建议您不要禁用"X-Frame-Options"
header 并在 iframe 中使用您的应用程序。
这会带来安全风险,您可以在以下位置阅读更多信息:这个答案 https://stackoverflow.com/a/9428051/11430047.
现在解释一下您所看到的行为。
Spring Security 使用Session
cookie 来存储用户的会话。
Cookie 与域关联,因此,例如,如果有一个 Cookie 与域关联stackoverflow.com
那么该 cookie 将包含在任何请求中stackoverlow.com
.
为了控制这种行为,cookies 还有一个名为SameSite
.
The SameSite属性 https://web.dev/samesite-cookies-explained/可以有 3 个值,None
, Lax
, Strict
或者它可以被取消设置并且没有任何值。
当值为None
,它的行为如上所述(包含在所有请求中)。
当值为Lax
,那么 cookie 将只包含在顶级导航中GET
要求。
The Session
Spring Security 使用的 cookie 不会设置SameSite
属性。
目前(2020 年 3 月),某些浏览器(例如 Firefox 和 Edge)将 unset 属性视为与None
.
然而,Chrome 正在尝试将 unset 属性视为与Lax
.
您可以在以下内容中阅读更多相关内容Chrome 平台状态 https://chromestatus.com/feature/5088147346030592.
综上所述,在使用 Chrome 时,Session
cookie 被视为有SameSite
set to Lax
.
由于在 iframe 中渲染应用程序不是顶级导航,因此Session
iframe 的请求中不包含 cookie,应用程序无法知道用户是否已登录。
您可以显式设置SameSite
归因于None
通过使用 Spring 会话。
我再次提醒您不要这样做,因为它会使您的应用程序容易受到 CSRF 和点击劫持攻击。
如果在考虑安全影响后,您认为有必要设置SameSite
归因于None
,您可以通过在依赖项中包含 Spring Session 并创建一个custom CookieSerializer https://docs.spring.io/spring-session/docs/2.2.2.RELEASE/reference/html5/guides/java-custom-cookie.html#custom-cookie-spring-configuration.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)