但是,当我使用邮递员时,所有路线均有效。但是在我的JavaScript应用程序中,只有开放的路由起作用(那些带有allowAll()的路由),即使我传递了正确的JWT token , protected 路由也会在下面返回错误。
这是我的 Spring 安全配置:
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
class AppSecurity(val authManager: AuthenticationManager,
val securityContextRepository: SecurityContextRepository) {
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(authManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.pathMatchers(HttpMethod.POST, "/apiv1/user", "/apiv1/user/login").permitAll()
.pathMatchers(HttpMethod.GET, "/apiv1/user", "/apiv1/user/**").permitAll()
.pathMatchers(HttpMethod.POST, "/apiv1/shopping/**").hasAnyRole("ROLE_CLIENT", "ROLE_ADMIN")
.pathMatchers(HttpMethod.GET, "/apiv1/shopping/**").hasAnyRole("ROLE_CLIENT", "ROLE_ADMIN")
.anyExchange().authenticated()
.and().build()
}
@Bean
fun corsWebFilter(): CorsWebFilter {
val corsConfig = CorsConfiguration()
corsConfig.allowCredentials = true
corsConfig.allowedOrigins = mutableListOf("*")
corsConfig.allowedMethods = mutableListOf("*")
corsConfig.allowedHeaders = mutableListOf("*")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", corsConfig)
return CorsWebFilter(source)
}
}
最佳答案
我设法按照下面链接中的官方文档进行了修复。要点是必须在 Spring 安全之前对CORS进行处理。
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#cors
这是我的最终代码:
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
class AppSecurity(val authManager: AuthenticationManager,
val securityContextRepository: SecurityContextRepository) {
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http.cors(Customizer.withDefaults()).csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(authManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.pathMatchers(HttpMethod.POST, "/apiv1/user", "/apiv1/user/login").permitAll()
.pathMatchers(HttpMethod.GET, "/apiv1/user", "/apiv1/user/**").permitAll()
.pathMatchers(HttpMethod.POST, "/apiv1/shopping/**").hasAnyRole("ROLE_CLIENT", "ROLE_ADMIN")
.pathMatchers(HttpMethod.GET, "/apiv1/shopping/**").hasAnyRole("ROLE_CLIENT", "ROLE_ADMIN")
.anyExchange().authenticated()
.and().build()
}
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowCredentials = true
configuration.allowedOrigins = mutableListOf("*")
configuration.allowedMethods = mutableListOf("*")
configuration.allowedHeaders = mutableListOf("*")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}
}