在Angular应用程序中使用Spring Security和Okta时,可能会遇到跨域问题。以下是解决该问题的一种方法,其中包含了代码示例。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and() // 允许跨域请求
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); // 允许的源
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE")); // 允许的方法
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
proxy.conf.json
文件中添加以下内容:{
"/api/*": {
"target": "http://localhost:8080", // Spring Boot应用程序的URL
"secure": false,
"logLevel": "debug"
}
}
package.json
文件中的scripts
部分添加以下内容:"start": "ng serve --proxy-config proxy.conf.json"
通过以上步骤,您的Angular应用程序将与Spring Security和Okta一起处理跨域请求。在示例中,我们允许来自http://localhost:4200
的请求,并将其代理到http://localhost:8080
。您可以根据自己的需求进行相应的更改。
上一篇:Angular/Spring Boot与Keycloak一起抛出403错误。
下一篇:Angular/SpringBoot:AngularService在进行Http请求时使用了localhost:4200而不是localhost:8080。