Override CORS policy in java springboot - spring-boot

I am trying to have my frontend server pull an http request from my backend server, but am getting the following error in my browser console:
Access to XMLHttpRequest at 'http://localhost:8080/run' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I know this is a security protocol, but is there an easy way to override this issue and allow for port 8080 (my backend) to return calls from port (3000)?
edit: I am using java springboot as my backend framework and React as my frontend framework
edit 2: I installed and used the Moesif Origin & CORS Changer extension and it works, I just would like to know if there is a more permanent workaround.

A quick approach is to add #CrossOrigin (import is org.springframework.web.bind.annotation.CrossOrigin) to your Rest Controller(s).

You can use CRA proxy setting, too.

This may help:
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}

Related

the probem Cors whene i send request from react to spring boot

i have application spring boot back end and i add this in the AuthorizationFilter
response.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
whene i log in it works but whene i try to to exu=ecute an other request it send me this error:
Access to fetch at 'http://localhost:8080/tasks' from origin 'http://localhost:3000' 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.
i dont know why there is no the problem of Cros in the authentication beacause it is the same domaine
please help me to solve the problem
There is a better way to handle and configure CORS globally in Spring Boot which should solve your problem:
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000");
}
}
For more details please check this article.

Issues setting up API on Elastic Beanstalk with HTTPS requests

So, I've been trying for time to get the following working:
Hosting front-end application on S3 Bucket (with HTTPS support)
Hosting Spring Boot API with Elastic Beanstalk (with HTTPS support)
Make requests from front-end application to API (with HTTPS support)
My current setup for EBS is, the API is sitting behind a load balancer with Route 53 directing incoming requests to the load balancer, which then sends an internal HTTP request to EBS.
It was quite painful for me to get to this point (This is all pretty new to me) and after getting this set up, I'm receiving a CORS error when trying to make a request to the API from my front-end. I'm not seeing anything in the logs and my Spring Boot CORS is set up to accept all, so this leads me to believe that the Load Balancer is causing the CORS error.
I'm wondering if I'm on the right track at all? Could the load balancer be causing this issue? Can it be resolved?
Add this code in your main class below main function
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}

Why is my website available for 2 URL: when I search it with http and https?

If I type www.website.com I end up in the http with the not secure tag.
Instead, if I want to find it with the secure https, I have to search for it as https://www.....com.
Does anyone know how to fix this?
If you've already configured your SSL certificate, then it should be a cake walk for you. In any other case here is a link..
Now, you can redirect HTTP request and enforce the use of HTTPS when your app is running on Heroku by adding the following configuration to your Spring Boot app.
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel()
.requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
.requiresSecure();
}
}
If you already have a WebSecurityConfigurerAdapter implementation, then add the above configuration to it.
This configuration tells Spring to redirect all plain HTTP requests back to the same URL using HTTPS if the X-Forwarded-Proto header is present. Heroku sets the X-Forwarded-Proto header for you, which means the request will be redirected back through the Heroku router where SSL is terminated.
Source: Heroku Devcenter

CORS on Webjars in Spring Boot?

I'm using Spring Boot 1.4.0.M2 and Spring 4.3.0.RC1, trying to enable CORS support in a simple app. I have this added:
#Bean
public WebMvcConfigurer webMvcConfigurerAdapter() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
I also have webjars pulled in through Gradle, such as:
compile('org.webjars:jquery:2.2.3')
The CORS support works fine with my REST API (via #RestController), but somehow it doesn't seem to work when accessing my webjars. For example (UPDATE: less confusing example), requesting:
http://example.org/webjars/bootstrap-datepicker/1.6.0/package.json
gets a response with the correct content but lacking the expected CORS headers, which of course defeats any actual CORS request. I can't figure out why that would be an exception to the /** mapping. How do I fix it?
JavaScript doesn't need cors configuration . In other words, you can access JavaScript resources from a site which doesn't enable cors.
From wiki site, we can obvious know that a website can freely embed images, stylesheets, scripts, iframes, videos and some plugin content (such as Adobe Flash) from any other domain. So even if you are enabling CORS on your website, but your resource is javascript, so the request does not add CORS header.
Your code snippet copied from documentation is just a sample of showing how to enable CROS in a quick way. This code snippet is not complete. Using this will mess up what WebMvcAutoConfigurationAdapter provided for you.

owin cors or web api cors

there are 100s of question on CORS on web-api, and on how to enable CORS, there is a different answer each one provides. I am so confused and dont know which answer is correct. And the problem is none of the answers actually explains it point wise, what each line of code does, so that I can understand and solve my problem rather than copy-pasting the code.
anyways, the question is: I am using asp.net web api 2 using owin. And i need to enable CORS. how do I do it? There is cors settings for OWIN
application.UseCors(CorsOptions.AllowAll);
and there is cors settings for asp.net web api
var cors = new EnableCorsAttribute("*", "*", "*", "*");
config.EnableCors(cors);
which one should I use given I am not using OAUTH (I am specifying this because answers on SO differ on when we use OAUTH v/s when we dont use it).
Do i need to enable CORS for both OWIN & WEB-API or only for one of them. There is issue if both are enabled, read here
It would be really helpful if someone can explain me the difference between
OWIN CORS
WEB API CORS
CORS with OAUTH using OWIN/WEBAPI
Also there are answers for self-hosted web api against owin hosted web-api, which further adds to the confution :(, sorry for the rant
You are supposed to use Web API's CORS if you need CORS applied to your API Controllers. For everything else (like a token service) you're stuck with having to use Owin.Cors.
If you end up using both, you'll need to make sure they don't overlap and apply CORS twice to the same request.
Web API 2.2 makes it easy to enable CORS by providing the EnableCorsAttribute.
Basic Usage
[EnableCors("*", "*", "*")]
public class ResourcesController : ApiController
{
...
Attribute definition
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)]
public EnableCorsAttribute(
string origins,
string headers,
string methods
)
To enable CORS globally use
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
// ...
}
}
You will also need to install the CORS package from nuget
Install-Package Microsoft.AspNet.WebApi.Cors
There is a way to fix this. Since OWIN and ASP.NET.CORS libraries are working simultaneously. Owin token or authentication method needs to be configured to enable CORS separately from all other API controllers.
Fist thing first, don't use cors with Owin in Startup.cs :
public void Configuration(IAppBuilder app)
{
//app.UseCors(CorsOptions.AllowAll);
Find GrantResourceOwnerCredentials method and add Access-Control-Allow-Origin to context so when it returns a call after authentication is completed that browser finds the header and accepts it.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost" });
Now install Microsoft.AspNet.WebApi.Cors package from Nuget to your webapi project, and add this to Register method
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");
config.EnableCors(cors);
Worked for me.

Resources