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

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;
}

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.

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);

CORS Issue during preflight browser request [duplicate]

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.

Receive Authorization header on anonymous url using Spring Boot

How can an Authorization header be accessed on anonymous urls?
My security configuration looks like:
http
.authorizeRequests()
.antMatchers("/login", "/legacy-login").anonymous()
.antMatchers("/things/*").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic()
Authentication in general works fine. However, on /legacy-login I need to do some migration and need to access the authorization header without spring boot managing the authorization. Although /legacy-login is marked anonymous as soon as there are requests, spring intercepts the request and tries to authorize itself (what then results into 401).
How can I make Spring let the auth header through on that single url?
I foudn one solution myself. Instead of fiddleing around with .anonymous() and .permitAll() I added /legacy-login as ignore rule:
override fun configure(web: WebSecurity) {
super.configure(web)
web.ignoring()
.antMatchers("/legacy-login")
}

Resources