【发布时间】:2019-12-16 16:53:10
【问题描述】:
TL;DR
每次 localhost:4200(通过 cors 过滤器)向 localhost:8080 发出 http 请求时,它都会丢失 sessionscope bean,该 bean 持有身份验证,这基本上使它无法使用 403 进行所有调用。排除第一个 http 请求(不落后于 Spring Security)
我有一个在 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
@SessionScope
public 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:4200 在向 localhost:8080 发出请求时会在每次调用时创建一个新会话? (以及应该更改哪些配置来解决此类问题?)
附录 1º:如果我发表评论
@EnableGlobalMethodSecurity(prePostEnabled = true)
该代码适用于 localhost:4200(我的意思是他不再拥有 403 代码)但可能仍在每个请求中使用另一个会话范围 bean
附录 2º:
现在可以使用了
我所要做的就是将 ssl 放在 ng serve 配置中(它在 localhost:8080 但不是 4200)并且 JSessionId 开始工作!
【问题讨论】:
标签: java spring spring-boot spring-security cors