Skip to content

Commit

Permalink
[Fix] Cors 에러
Browse files Browse the repository at this point in the history
  • Loading branch information
jiyunio committed Nov 14, 2024
1 parent 49c6bd9 commit 448bd77
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 26 deletions.
27 changes: 1 addition & 26 deletions src/main/java/com/basic/study/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,43 +1,18 @@
package com.basic.study.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
public class SecurityConfig {
@Value("${web.port}")
private String port;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.httpBasic(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors
.configurationSource(corsConfigurationSource()));

.csrf(AbstractHttpConfigurer::disable);
return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:" + port));
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
20 changes: 20 additions & 0 deletions src/main/java/com/basic/study/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.basic.study.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${web.port}")
private String port;

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:" + port)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*");
}
}

0 comments on commit 448bd77

Please sign in to comment.