CORS Issue during preflight browser request [duplicate] - spring-boot

This question already has an answer here:
Spring Boot CORS with HTTPS failing
(1 answer)
Closed 2 years ago.
While trying to connect to my Rest APIs via Angular, I am running into what seems to be a fairly straight forward CORS issue:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://mserverIP:port/apicontext/getsitebyuserid/userId. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
My APIs are setup in Springboot and I have already tried following:
Set up #CrossOrigin(origins = "*") annotation at class and method levels. Also enabled GET, POST, OPTIONS for cross origin as well as allowed for all the headers.
Setup the added CORS configuration globally with following code:
httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
httpServletResponse.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,HEAD");
httpServletResponse.setHeader("Access-Control-Max-Age", "7200");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
"Content-Type, X-Requested-With, accept, authorization, Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
Tried it via proxy authentication (authentication being used is JWT).
This piece of information might be vital: for an unauthenticated API, the CORS issue doesn't happen but for the protected routes, it returns 403. The problem for protected routes happen even if I have not set authentication header to true.
Also, I have noticed earlier that during preflight, its combination of 2 headers that's causing the issue. If I send origin: http://localhost:4200 and Access-Control-Request-Method: GET it errors out. But if I sends one of the headers it works. During the OPTIONS request, if there's a request header called origin, the request fails. If I remove origin from postman it works.

First of all if you are using spring security then you can get rid of the class level annotations and handle the CORS configuration globally in your security configuration class like :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.
cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/login").hasRole("ADMIN")
.antMatchers("/Signup").hasRole("USER")
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied")
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailService));
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); //or * if you want to allow all
configuration.setAllowCredentials(true);
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Secondly, you don't need the cors filter to manually add the response headers to every request because if you configure the cors configuration correctly , springboot will automatically add all the necessary headers in response through the CorsFilter . So, if you are using cors with spring security it is easier to us the provided filter with your configurations. Also, ensure that the springboot auto-configuration is working for you as using annotation #EnableWebMvc will disable the auto-configurations and in that case you will have to handle cors using filter probably.

Related

Spring Auth Server 1.0.0 (w/ Spring Boot 3.0.0) CORS configuration not working for .well_known endpoints

I am trying to use the Spring Boot Auth Server sample code with a ReactJS frontend that will be hosted as a separate service. However, I am getting the following error.
localhost/:1 Access to fetch at 'https://8f5d3990e976.ngrok.io/.well-known/openid-configuration' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm trying to configure CORS mentioned in this comment.
https://github.com/spring-projects/spring-authorization-server/issues/110#issuecomment-707964588
The class WebSecurityConfigurerAdapter was deprecated and removed so I added it a little differently.
#Bean
#Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:3000");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/oauth2/**", config);
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.cors().configurationSource(source);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0
// #formatter:off
http
.exceptionHandling(exceptions ->
exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
// #formatter:on
return http.build();
}
Note: The reason I added the source with a local variable is I got this IDE error
If anyone would be able to help with this I would greatly appreciate it. Cheers.

Why the spring-cloud with the gatway ignore the cors property defined in application.properties?

I'm trying to build a microservices spring-boot application using spring-cloud and spring-gateway. In my application there is a api-gateway application that handle all the request and later will dispatch those request to the right microservice.
For the front-end I'm using angular and for test the endpoints I'm using postman. At the moment I'm having a CORS problem. I've configured the api-gateway in this way:
spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping=true
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedOrigins=*
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedHeaders=*
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedMethods=*
According to the documentation it should be enough to allow a client to make a request without problem.
Also I've configured all the gateway route in this way...
spring.cloud.gateway.routes[8].id=entity-service
spring.cloud.gateway.routes[8].uri=lb://entity-service
spring.cloud.gateway.routes[8].predicates[0]=Path=/api/entity/hello
My security config also is the one below
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity serverHttpSecurity) {
serverHttpSecurity
.authorizeExchange(exchange ->
exchange.pathMatchers("/eureka/**")
.permitAll()
.anyExchange()
.authenticated())
.cors()
.and()
.csrf()
.disable()
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt);
return serverHttpSecurity.build();
}
}
Said that, if for instance I make a request with postman to the path /api/entity/hello I get the correct response. If I'm using the angular client and try to access an end-point , first an OPTIONS preflight request is made and return:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/entity/hello. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.
then the GET request for the ..../hello path is made and the result is the same.
I am using spring-boot 2.7.3 and the latest spring-boot-cloud and gateway package.
Do you have any idea how to fix this? Any help will be appreciated.
Thanks to all
Try adding CorsConfigurationSource bean to your config class.
#Bean
public CorsConfigurationSource corsConfigurationSource(GlobalCorsProperties globalCorsProperties) {
var source = new UrlBasedCorsConfigurationSource();
globalCorsProperties.getCorsConfigurations().forEach(source::registerCorsConfiguration);
return source;
}

How deactivate CORS in a Spring Boot API (Version 2.2.6)

I am currently working on a React Front-End with an already existing Spring Boot Backend.
When developing locally i ran into the typicall CORS Error:
Access to fetch at 'http://localhost:8180/api/data/firms' from
origin 'https://localhost:8087' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
runtime.js:98 GET http://localhost:8180/api/data/firms net::ERR_FAILED
I already tried most of the solutions mentioned in this post however nothing really helped. By adding one of these snippets
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}
#Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
or creating a CorsFilter the CORS Error was gone but now the API always returned a HTTP 500 Error.
Does anyone know a solution for my problem?
You can add this in your controller class.
#CrossOrigin(origins = "${cross.origin}")
#RestController
application.properties
cross.origin=https://localhost:8087
I've added new answer for Spring Boot.
Additionally, if you are using create-react-app, you will avoid CORS problem to set up proxy.
(In this case, it is not required to change Spring Boot settings.)
package.json:
"proxy": "http://localhost:8180",

How to setup ForwardedHeaderFilter for login using Spring Security without Spring Boot?

I am looking to setup the ForwardedHeaderFilter in spring security so I can let spring know which protocol to use after login. I have several app servers behind a load-balancer (using ssl termination) and spring security is redirecting the user using http (instead of https). Because of this, my users are now getting a obtrusive warning message. The only examples I can find online are with spring boot which I do not implement.
I thought of using "addFilterBefore()" method to my security configuration, but the filter is never called.
Any ideas?
// Apply sameOrigin policy for iframe embeddings
http.headers().frameOptions().sameOrigin();
// ********* Add filter here? *******
http.addFilterBefore(new ForwardedHeaderFilter(), ChannelProcessingFilter.class);
// Authorization filters
http.authorizeRequests().antMatchers("/sysAdmin/**", "/monitoring/**").access("isFullyAuthenticated() and hasRole('GOD')");
http.authorizeRequests().antMatchers("/app/**").authenticated();
http.authorizeRequests().antMatchers("/**").permitAll();
http.formLogin()
.loginPage("/public/login.jsp")
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/app/Dashboard.action", false)
.failureHandler(customAuthenticationFailureHandler());
// Disable so that logout "get" url works (otherwise you have to do a html form)
http.csrf().disable();
http.logout().logoutSuccessUrl("/public/login.jsp");
http.sessionManagement()
.invalidSessionUrl("/public/expiredSession.jsp?expiredId=2")
.maximumSessions(2)
.sessionRegistry(sessionRegistry())
.expiredUrl("/public/expiredSession.jsp?expiredId=3");
I ended up adding the filter like this and everything seemed to work
// Added for load balancer headers (X-Forwarded-For, X-Forwarded-Proto, etc)
http.addFilterBefore(new ForwardedHeaderFilter(), WebAsyncManagerIntegrationFilter.class);

Spring Security CookieBasedCSrf not working

I am developing a RESTful Spring backend with an Angular2 front end. I store my access token (JWT implementation) in a httpOnly Cookie. To protect myself from XSRF attacks on post requests, I need to enable XSRF protection on all pages, except the login page. Per the Spring Security guide here, I have enabled CookieCsrfTokenRepository.
However, when I hit a public API (GET), the XSRF-TOKEN is not set. Also, when I submit my login form data from Angular2, the system thows a 'invalid csrf token' error. Below is my WebSecurityConfig:
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.exceptionHandling()
.authenticationEntryPoint(this.authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token refresh end-point
.antMatchers(TOKEN_CSRF_ENTRY).permitAll()
.and()
.authorizeRequests()
.antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected API End-points
.and()
.cors()
.and()
.addFilterBefore(buildAjaxLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
You should not get a CSRF token by HTTP GET, see Spring Security Reference:
Use proper HTTP verbs
The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. Specifically, before Spring Security’s CSRF support can be of use, you need to be certain that your application is using PATCH, POST, PUT, and/or DELETE for anything that modifies state.
This is not a limitation of Spring Security’s support, but instead a general requirement for proper CSRF prevention. The reason is that including private information in an HTTP GET can cause the information to be leaked. See RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s for general guidance on using POST instead of GET for sensitive information.
You should not exclude login from CSRF protection, see Spring Security Reference:
Logging In
In order to protect against forging log in requests the log in form should be protected against CSRF attacks too.
But you can exclude some URLs from and include some HTTP verbs to CSRF protection, see Spring Security Reference:
You can also specify a custom RequestMatcher to determine which requests are protected by CSRF (i.e. perhaps you don’t care if log out is exploited). In short, if Spring Security’s CSRF protection doesn’t behave exactly as you want it, you are able to customize the behavior. Refer to the Section 41.1.18, “<csrf>” documentation for details on how to make these customizations with XML and the CsrfConfigurer javadoc for details on how to make these customizations when using Java configuration.
Have you tried to enable withCredentials: true?
This is how I write my post server in Angular2.
this.http.request(
path,
{
method: RequestMethod.Post,
body: body,
headers: customHeaders,
withCredentials: true
}
)
.map...
.catch...
I have the same config in WebSecurityConfig.
I do have a working example using Angular 2 and Spring Boot that uses CookieCsrfTokenRepository.
My Angular 2 API service
My WebSecurityConfig
Github repo: angular-spring-starter

Resources