每次 localhost:4200(通過 cors 過濾器)向 localhost:8080 發出 http 請求時,它會丟失保存身份驗證的 sessionscope bean,這基本上使它無法通過 403 進行所有調用。不包括第一個 http 請求(不在后面)彈簧安全)我有一個在 localhost:8080 中運行良好的 spring boot 應用程序。我們正在其中創建一個角度 iframe,它也運行良好(當部署在 localhost:8080 上時)但是當我們在 localhost:4200 (ng serve) 上執行它時它不會工作它開始抱怨 cors 所以我有以下配置,除了我添加的關于 cors 的所有內容。@Configuration@Profile({"dev"})@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class springDevConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception{ http.csrf().disable(); http.headers().frameOptions().sameOrigin(); http.headers().cacheControl().disable(); http.cors().configurationSource(corsConfigurationSource()) .and().authorizeRequests().anyRequest().permitAll(); } @Bean public CorsConfigurationSource corsConfigurationSource(){ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins( ImmutableList.of("http://localhost:4200")); configuration.setAllowedMethods(Arrays.asList( RequestMethod.GET.name(), RequestMethod.POST.name(), RequestMethod.OPTIONS.name(), RequestMethod.DELETE.name(), RequestMethod.PUT.name())); source.registerCorsConfiguration("/**", configuration); return source; }}我的會話 bean 相當簡單@Component@SessionScopepublic class UserSession { //Holds the Authorities for the prePostEnabled User user; ...}為了初始化用戶,我向某個端點(未受保護的)發出請求并在代碼中執行類似的操作...User user = new User(id, "", authorities);Authentication auth = new UsernamePasswordAuthenticationToken(user, null,authorities));SecurityContextHolder.getContext().setAuthentication(auth);Usersession.setUser(user);...當我在 localhost:8080 上發出 http 請求時,后續的 http 請求具有相同的會話。但是當我嘗試從 localhost:4200 向 localhost:8080 發出請求時,每個請求似乎都獲取了不同的 UserSession / 也許打開了一個新會話?(在所有受保護的端點上給我 403)真正發生了什么,為什么在向 localhost:8080 發出請求時 localhost:4200 每次調用都會創建一個新會話?(應該更改哪些配置來解決此類問題?)
1 回答

慕容708150
TA貢獻1831條經驗 獲得超4個贊
您能否展示更多有關如何嵌入 iframe 以及為原始頁面提供什么服務的信息?
似乎正在發生的事情是您在沒有意識到的情況下有效地發出跨域請求。8080 和 4200 是不同的域,如果頁面的一部分從一個域加載,而部分頁面(即 iframe)從另一個域加載,則構成跨域請求,并且一個域發送的 cookie 不會應用于對該域的請求其他,因此不共享會話范圍。此外,如果您向加載原始頁面的域以外的域發出 Ajax 請求,除非您設置 CORS,否則默認情況下它們會被拒絕。這解釋了為什么你必須這樣做。
您必須確保頁面的所有部分(包括 iframe 和 Ajax 請求)都是從同一域加載的,或者您有其他方法可以將會話附加到請求。通常,JSESSIONID cookie 用于此目的。此 cookie 是否在初始響應中發送?
您通常有一個應用程序服務于前端,包括初始頁面(例如 4200 上的應用程序),以及一個僅響應 API 調用的應用程序(例如 8080 上的應用程序),并配置了 CORS。這樣所有對后端的調用都通過同一個域完成,并且 cookie 得到正常應用。
添加回答
舉報
0/150
提交
取消