add CORS
Change-Id: Ia5081c931dfae660ccdf2737ce3a032e71363225
diff --git a/src/main/java/com/example/g8backend/config/SecurityConfig.java b/src/main/java/com/example/g8backend/config/SecurityConfig.java
index 82c9946..7ab3aa1 100644
--- a/src/main/java/com/example/g8backend/config/SecurityConfig.java
+++ b/src/main/java/com/example/g8backend/config/SecurityConfig.java
@@ -11,6 +11,11 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.CorsConfigurationSource;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+
+import java.util.List;
@Configuration
@EnableWebSecurity
@@ -30,12 +35,11 @@
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
+ .cors()
+ .and()
.authorizeHttpRequests(auth -> auth
- // 管理员接口需ADMIN角色
.requestMatchers("/admin/**").hasRole("ADMIN")
- // 用户签到接口需认证
.requestMatchers("/user/signin").authenticated()
- // 其他请求允许匿名访问(感觉这里应该还需要做修改,暂时先放着)
.anyRequest().permitAll()
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
@@ -43,6 +47,19 @@
}
@Bean
+ public CorsConfigurationSource corsConfigurationSource() {
+ CorsConfiguration config = new CorsConfiguration();
+ config.setAllowCredentials(true);
+ config.setAllowedOriginPatterns(List.of("http://localhost:8081")); // ✅ 尽量具体写域名
+ config.setAllowedHeaders(List.of("*"));
+ config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
+
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+ source.registerCorsConfiguration("/**", config);
+ return source;
+ }
+
+ @Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index 9c851a3..dbde0cf 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -4,6 +4,8 @@
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.sql.init.mode=always
#logging.level.root=DEBUG
+server.address=0.0.0.0
+server.port=8080
mybatis-plus.mapper-locations=classpath*:/mapper/**/*.xml