CorsConfig.java
package com.github.jenkaby.bikerental.shared.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
private final CorsProperties corsProperties;
public CorsConfig(CorsProperties corsProperties) {
this.corsProperties = corsProperties;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(corsProperties.allowedOrigins().toArray(String[]::new))
.allowedMethods(corsProperties.allowedMethods().toArray(String[]::new))
.allowedHeaders(corsProperties.allowedHeaders().toArray(String[]::new))
.allowCredentials(corsProperties.allowCredentials())
.maxAge(corsProperties.maxAge());
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(corsProperties.allowedOrigins());
config.setAllowedMethods(corsProperties.allowedMethods());
config.setAllowedHeaders(corsProperties.allowedHeaders());
config.setAllowCredentials(corsProperties.allowCredentials());
config.setMaxAge(corsProperties.maxAge());
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}