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

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.

Related

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

CORS issue with website calling a REST API on https

I have a website running on https.
I want this website to communicate with a REST Api service running on a AWS EC2 server.
This service is implemented with Spring Boot and the Controller class contains the #CrossOrigin annotation with the origin website as a parameter.
However I am getting following error while doing a POST request from the website with the service listening on port 443 with a self signed certificate:
Access to XMLHttpRequest at x from origin y 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.
And following one while doing a GET request:
Access to XMLHttpRequest at x from origin y has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I also declared localhost in the service #CrossOrigin annotation.
It is failing with same error as above if I have my service run on port 443 with a self signed certificate, but it is working fine if I have my service running on port 8080 without SSL.
Do you know what I am doing wrong?
Also I guess that if I manage to solve the CORS issue I will still have a problem, as my certificate is self signed.
How can I install a public certificate for a REST Api running in EC2 for example?
Thanks!
Add the config mentioned below to your spring-boot project.
#Configuration
public class CorsConfig {
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(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",

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.

Spring 4.2's native Global CORS support won't work with CAS filterProcessesUrl

i am trying to switch to spring 4.2's native Global CORS support after i upgrade to spring-boot 1.3, but it seemed won't work with CAS filter process url(/login/cas).
Originally, i was using spring-boot 1.2.7 with spring 4.2 and spring-security 4.0.2, and using self made filtered based cors support. And either my own rest service or CAS ST validation URL worked well. After i upgraded to spring-boot 1.3 with coming in spring and spring-security version. It stopped working.
After some digging, fixed this by AddFilterBefore. So filtered based CORS seemed work well too with spring-boot 1.3.0 + spring-security-cas.
However, i want to use native Global CORS, but it seemed the CAS ST validation URL(/login/cas) can't be recognized, though other rest endpoints are OK.
Please help.
The setup is quite straight forward.
#Configuration
public class CorsConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
And following are some trafic:
Request URL:http://localhost:9000/login/cas?ticket=ST-1357-15aQrv93jGEUsQpQRF1P-cas01.example.org
Request Method:GET
Status Code:302 Found
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Thu, 19 Nov 2015 09:19:31 GMT
Expires:0
Location:http://localhost:9000/
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
and following are console errors:
XMLHttpRequest cannot load http://localhost:9000/login/cas?ticket=ST-1357-15aQrv93jGEUsQpQRF1P-cas01.example.org. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
CORS native support is done by default at Spring MVC HandlerMapping level, so it is expected that your CAS filter will not be CORS enabled, since it handles request earlier.
One option to consider is using the org.springframework.web.filter.CorsFilter we also provide with Spring Framework 4.2 with the AddFilterBefore approach.
Be aware that CorsConfiguration has not the same default configuration than #CrossOrigin or CorsRegistry, so you need to define most of the properties yourself, for example:
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // you USUALLY want this
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
source.registerCorsConfiguration("/**", config);
CorsFilter filter = new CorsFilter(source);
// ...

Resources