Skip to content

Commit 6422e36

Browse files
authored
fix: cors not disabled (#200)
1 parent f005d3c commit 6422e36

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/main/java/com/sterul/opencookbookapiserver/configurations/security/WebSecurityConfiguration.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package com.sterul.opencookbookapiserver.configurations.security;
22

33
import java.util.Arrays;
4+
import java.util.Collections;
45
import java.util.List;
56

67
import org.springframework.beans.factory.annotation.Autowired;
78
import org.springframework.context.annotation.Bean;
89
import org.springframework.context.annotation.Configuration;
10+
import org.springframework.http.HttpMethod;
911
import org.springframework.security.authentication.AuthenticationManager;
1012
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
1113
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@@ -18,6 +20,7 @@
1820
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
1921
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
2022
import org.springframework.security.web.util.matcher.RequestMatcher;
23+
import org.springframework.web.cors.CorsConfiguration;
2124

2225
import com.sterul.opencookbookapiserver.configurations.security.requestfilters.JwtRequestFilter;
2326

@@ -70,7 +73,7 @@ private RequestMatcher allowedPathRequestMatcher() {
7073
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
7174

7275
// Cors and csrf not needed in an api server
73-
http.cors(configurer -> configurer.disable());
76+
http.cors(configurer -> configurer.configurationSource(c -> allowAllCorsConfig()));
7477
http.csrf(conf -> conf.disable());
7578

7679
// Allow frames needed for h2 console
@@ -93,7 +96,21 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
9396
return http.build();
9497
}
9598

96-
@Bean
99+
private CorsConfiguration allowAllCorsConfig() {
100+
List<String> permittedCorsMethods = Collections.unmodifiableList(Arrays.asList(
101+
HttpMethod.GET.name(),
102+
HttpMethod.HEAD.name(),
103+
HttpMethod.POST.name(),
104+
HttpMethod.PUT.name(),
105+
HttpMethod.DELETE.name()));
106+
107+
var corsConfiguration = new CorsConfiguration().applyPermitDefaultValues();
108+
corsConfiguration.setAllowedMethods(permittedCorsMethods);
109+
return corsConfiguration;
110+
111+
}
112+
113+
@Bean
97114
public AuthenticationManager authenticationManager(HttpSecurity http)
98115
throws Exception {
99116
return http.getSharedObject(AuthenticationManagerBuilder.class)

0 commit comments

Comments
 (0)