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

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.

Related

HttpSessionIdResolver not working on Authentication basic

Im trying to run a simple REST example, exposing repositories through data-rest and spring sessions with x-auth-token session, but x-auth-token is not shared after http basic authentication.
I installed my spring boot and repositories working good, then I expose the x-auth-token through
#Configuration
#EnableJdbcHttpSession
public class HttpSessionConfig {
#Bean
public HttpSessionIdResolver httpSessionIdResolver() {
return HeaderHttpSessionIdResolver.xAuthToken();
}
}
The problem is , every request that is not authneticated is sending the x-auth-token on the headers, but after I login and I authenticate with basic authentication, the x-auth-token is not sending on headers, instead is sending JSESSION and SESSION through cookies. :S someone know why?
Im using this documentation -> https://docs.spring.io/spring-session/reference/http-session.html#httpsession-rest with spring boot, but not working.

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",

Override CORS policy in java springboot

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

How to authenticate some URL and ignore anything else

I want to manage security policy like below. ( HTTP Basic Authorization)
Apply authentication following URLs.
"/foo/", "/bar/"
Ignore anything else URLs. ( Even though requests have Authorization field in header)
I know permitall(). But permitall() is not suitable because it apply security policy when request has Authorization field in headers.
If you want ignore particular url then you need to implement this method.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/static/**");
}
}
You can put your url in place of /static/** in which you want no authentication apply.
Your example means that Spring (Web) Security is ignoring URL patterns
that match the expression you have defined ("/static/**"). This URL is
skipped by Spring Security, therefore not secured.
Read the Spring Security reference for more details:
Click here for spring security details

Angular ts (front-end) + spring boot (back-end) OAuth2 flow

I want to implement authorization via Google and Microsoft in my full stack app (Angular 6 for front-end, Spring boot for back-end) and I've got a problem.
I follow this scheme which describes how the flow should be implemented:
OAuth2 Authorization Flow:
The problem is with Step 4 where front-end should send authorization code to back-end. I just don't know which endpoint to use and how to configure it in Spring Security configuration.
This endpoint should get authorization code, check it on OAuth provider side, request access and refresh token and remember the authorized user.
Maybe there is an example of how it should be done? Google answers do not seem appropriate.
What I already did:
Added #EnableOAuth2Sso annotation to the security configuration. But this is not what I actually need, because it enables authorization on back-end side. (redirecting to Google page works from back-end, but I need from front-end)
#EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
...
}
Tried configuring Oauth2Login by myself.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository)
.authorizedClientService(new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository));
}
Gradle dependencies:
<pre>
compile 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.0.RELEASE'
compile 'org.springframework.security:spring-security-oauth2-jose'
compile 'org.springframework.security:spring-security-oauth2-client'
</pre>
What I expect:
Some endpoint on back-end side, which accepts authorization code. For example:
URL: localhost:8080/oauth2/authcode/google
<pre>
{
"authorization_code": "...."
}
</pre>
And returns access token:
<pre>
{
"access_token": "...",
"expires": "..."
}
</pre>
And what is happening in the middle: back-end exchanges authorization code to access token and refresh token and saves it to own DB.
Thank you!

Resources