Skip to content

Commit

Permalink
Merge pull request #489 from bounswe/bugfix/BE-484-bugfix-backend-cor…
Browse files Browse the repository at this point in the history
…s-error

#484 Default CORS Configuration is added.
  • Loading branch information
volcaniqueo authored Nov 27, 2023
2 parents bcc0a48 + f6a2f40 commit 8bedace
Showing 1 changed file with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -17,6 +18,11 @@
import org.springframework.security.crypto.password.PasswordEncoder;
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.Arrays;

@EnableWebSecurity
@Configuration
Expand Down Expand Up @@ -57,7 +63,7 @@ public PasswordEncoder passwordEncoder() {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// No need to give context-path, just give requestMapping and related Post, Get mappings etc.

http.csrf(csrf -> csrf.disable())
http.csrf(csrf -> csrf.disable()).cors(Customizer.withDefaults())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth ->
Expand All @@ -73,4 +79,15 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

0 comments on commit 8bedace

Please sign in to comment.