Spring security CORS Filter
Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}
}
Spring Boot Security CORS
Instead of using the CorsRegistry you can write your own CorsFilter and add it to your security configuration.
Custom CorsFilter class:
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request= (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", true);
response.setHeader("Access-Control-Max-Age", 180);
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
Security config class:
@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
CorsFilter corsFilter() {
CorsFilter filter = new CorsFilter();
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(corsFilter(), SessionManagementFilter.class) //adds your custom CorsFilter
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/authentication").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}
}
Cors Error when using CorsFilter and spring security
Use config.setAllowedOriginPatterns("*")
instead of config.setAllowedOrigins(Collections.singletonList("*"));
CORS errors using Spring Boot, Spring Security and React
Try using the global CORS config as shown in below code to allow CORS for all endpoints.
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedMethods(CorsConfiguration.ALL)
.allowedHeaders(CorsConfiguration.ALL)
.allowedOriginPatterns(CorsConfiguration.ALL);
}
};
}
}
Since spring boot 2.4 you are supposed to use allowedOriginPatterns
instead of allowedOrigins
. Also you cannot use wildcard '*' along with credentials : true
spring security CORS filter allows requests without the Origin header
As SLaks described in his comments to the answer, the CORS headers are automatically added and filled by a browser client and the CORS filtering only makes sense in such a scenario.
When a request comes from a "non-browser" client, any content can be passed in the Origin:
header, making it pointless to force the clients to add the header, and the server to reject a request without it.
Consequently the answers to the questions are:
- yes
- no, there's no point in doing this
- no
Related Topics
Failed to Install Android-Sdk: "Java.Lang.Noclassdeffounderror: Javax/Xml/Bind/Annotation/Xmlschema"
Gson - Convert from JSON to a Typed Arraylist<T>
Android/Java -- Post Simple Text to Facebook Wall
Converting a String to an Integer on Android
How to Add a Shadow and a Border on Circular Imageview Android
Place Cursor at the End of Text in Edittext
Why Does "String".Getbytes() Work Different According to the Operation System
Trying to Locate a Leak! What Does Anon Mean for Pmap
Running Java Program from Command Line Linux
How to Troubleshoot "Inconsistency Detected: Dl-Lookup.C: 111" (Java Result 127) Error
How to View My Realm File in the Realm Browser
How to Create a Bks (Bouncycastle) Format Java Keystore That Contains a Client Certificate Chain
Ionic Build Android Error When Downloading Gradle
How to Use Vectordrawable in Buttons and Textviews Using Android:Drawableright
Android - Setting a Timeout for an Asynctask
Getting Java.Net.Sockettimeoutexception: Connection Timed Out in Android
Getting Noclassdeffounderror When Using Common.Lang.Stringutils in Android Java Code
Emulate Annotation Inheritance for Interfaces and Methods with Aspectj