Spring Boot+Keycloak+Svelte认证请求设计及登录跳转问题求助
解决方案
1. 后端跨域与Security配置调整
跨域(CORS)配置
在Spring Boot中添加CORS配置,允许前端域名的跨域请求并支持凭证传递(Keycloak会话依赖Cookie):
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://127.0.0.1:5173") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
Spring Security + Keycloak规则配置
确保未认证访问/products时触发Keycloak登录重定向,登录成功后返回前端目标页面:
@Configuration @EnableWebSecurity public class SecurityConfig { private final KeycloakAuthenticationProvider keycloakAuthenticationProvider; public SecurityConfig(KeycloakAuthenticationProvider keycloakAuthenticationProvider) { this.keycloakAuthenticationProvider = keycloakAuthenticationProvider; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth .requestMatchers("/products").authenticated() .anyRequest().permitAll() ) .oauth2Login(oauth2 -> oauth2 .loginPage("/oauth2/authorization/keycloak") .defaultSuccessUrl("http://127.0.0.1:5173/products", true) ) .logout(logout -> logout .logoutSuccessUrl("http://127.0.0.1:5173/") ); return http.build(); } }
2. 前端Svelte页面逻辑修改
前端不能直接用AJAX静默请求受保护接口,需主动触发浏览器的重定向登录流程:
<script> import { onMount } from 'svelte'; let products = []; onMount(async () => { try { const response = await fetch('http://localhost:8081/products', { credentials: 'include' }); if (response.ok) { products = await response.json(); } else if (response.status === 302) { window.location.href = 'http://localhost:8081/products'; } } catch (error) { window.location.href = 'http://localhost:8081/products'; } }); </script> <h1>Products</h1> {#if products.length > 0} <ul> {#each products as product} <li>{product.name}</li> {/each} </ul> {:else} <p>Loading products...</p> {/if}
3. Keycloak客户端配置
- 客户端类型设为
public(SPA无后端密钥) - 有效重定向URI添加:
http://localhost:8081/login/oauth2/code/keycloak、http://127.0.0.1:5173/products - Web Origins添加:
http://127.0.0.1:5173
核心逻辑说明
- 前端访问
/products时,先尝试请求后端接口,未认证则跳转到后端/products触发Keycloak登录重定向 - 用户登录后,Keycloak回调后端认证端点,后端完成认证后重定向回前端
/products - 前端再次请求后端接口,此时已携带认证Cookie,获取数据并展示
内容的提问来源于stack exchange,提问作者strelok
相关产品推荐
相关产品推荐

