I'm using SpringBoot 2.5.6.
I tryto upload file via byte array in the FileController class:
#PostMapping("/uploadFileViaStream")
public JSONObject uploadFile1(#RequestBody byte[] bytes) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
String fileName = genUUID();
String fileId = null;
fileId = fileService.uploadFile("", fileName, inputStream);
Map<String, Object> map = new HashMap<>(1);
map.put("file", fileId);
return ZheliResult.ok(map);
}
And add #CrossOrigin(origins="*") on the FileController class.
The Chrome says No 'Access-Control-Allow-Origin' header is present on the requested resource. which is a CORS issue.
Then I delete #CrossOrigin(origins="*"), and add a configuration class:
#Configuration
public class MvcConfiguration implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH", "HEAD", "OPTIONS")
.maxAge(3600);
}
}
Still doesn't work.
Then I delete this and turn to Nginx to configure CORS:
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Allow-Headers *;
It does work but after a while the CORS problem appeared again.
Then I configure the SpringCloud Gateway in the bootstrap.yml:
gateway:
globalcors:
add-to-simple-url-handler-mapping: true
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders: "*"
allowedMethods: "*"
allowCredentials: true
The Chrome says:
The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
If I change * int the Nginx or Gateway to http://172.20.10.9:8080, The Chrome says:
The 'Access-Control-Allow-Origin' header contains multiple values 'http://172.20.10.9:8080, http://172.20.10.9:8080', but only one is allowed.
So can anyone help me?
I would simply add filter requests and allow CORS to pass. The HIGHEST_PRECEDENCE order is importand. Do not neave it out!
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"DELETE, GET, OPTIONS, POST, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}
Related
I'm getting error while sending signup information to java spring-boot project from angular. I've tried thousands ways to resolve it but all in vain. Can't figure it out whats stopping java project to accept the request.
Error in console:
Access to XMLHttpRequest at 'http://localhost:8090/bites/service/signup' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field domain is not allowed by Access-Control-Allow-Headers in preflight response.
Here's my java code:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
try {
System.out.println("inside filter>>>>");
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
chain.doFilter(request, response);
}catch(Exception ex) {
ex.printStackTrace();
}
}
I know that angular signup form is sending accurate request with credentials to the java project but on java side request is denying.
Seeking help.
I'm trying my java application to accept request from angular project
Could you add the configuration:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200");
}
};
}
}
I'm having trouble trying to send a custom header param from my frontend to the controller.
I've set the endpoint to get the header param:
public ResponseEntity<DashboardBean> atualizarDadosDashboard(#RequestHeader(name = "idEmpresa") Long idEmpresa){
But when I try to consume this endpoint, I get failed response and the application doesn't log any error.
Here I have the browser console showing the failed request:
The second dashboard request is a OPTIONS type. The first is the GET request.
Here you can see the failed request headers with the custom header "idEmpresa":
I'm using Angular on the frontend. As you can see below, I'm adding the header to the request:
....
protected httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': this.token,
'idEmpresa': String(this.idEmpresa)
})
};
atualizarDashboard(): Observable<DashboardModel> {
return this.httpClient.get<DashboardModel>(this.baseUrl, this.httpOptions);
}
....
On my spring boot application there is nothing on the logs about this request!!
Problem solved.
I have a CORS Filter in my application. I had to add my custom header param to the
Access-Control-Allow-Headers
list to allow it. After that, the endpoint was consumed and worked as expected.
This is how my Filter is now:
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {
private final Log logger = LogFactory.getLog(this.getClass());
#Override
public void init(FilterConfig fc) throws ServletException {
logger.info("SimpleCORSFilter loaded");
}
#Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"x-requested-with, authorization, Content-Type, " +
"Authorization, credential, X-XSRF-TOKEN, idEmpresa");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, resp);
}
}
#Override
public void destroy() {
}
}
I want to accept origin as http://192.168.1.35:4200 and I created the CORSFilter like this in the springboot:
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
public CORSFilter() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "http://192.168.1.35:4200");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PATCH, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, X-Auth-Token, Origin, Content-Type, Accept, Auth_Token");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void destroy() {
}
}
And I created the request like this to call the spring rest api from angular:
getAllUsers(): void {
this.accessToken = JSON.parse(window.sessionStorage.getItem('token')).access_token;
this.httpClient.get<User[]>(`${BASE_URL}/fam-users/user?access_token=${this.accessToken}`, httpOptions).subscribe(data => {
this.dataChange.next(data);
},
(err: ApiError) => {
this.snackBar.openSnackBar(err.error.message, 'close', 'red-snackbar');
});
}
When I send request, It says that
Access to XMLHttpRequest at 'http://192.168.1.35:8080/fam-users/user?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTAwNDMwODMsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiRkFfQU1FTkQiLCJGQV9ORVciXSwianRpIjoiOWViMzZjNzAtOGUwOS00YzViLWI0OWQtNDNmZTRhOTkzNDgzIiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsicmVhZCIsIndyaXRlIiwidHJ1c3QiXX0.IETZOJE8tIqNc249HmTcJHuZpZFY1TP4PLcbqUOF3qc' from origin 'http://192.168.1.35:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But all other requests from 'http://192.168.1.35:4200' are working fine.
Can Someone guide me to solve this issue?
There is a #CrossOrigin annotation in spring boo, for example:
#CrossOrigin(origins = "http://localhost:9000")
#GetMapping("/greeting")
public Greeting greeting(#RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
for more please have a look
This question already has answers here:
CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource
(8 answers)
Closed 4 years ago.
I am trying to add OAuth 2.0 in spring mvc app. User should be authenticated in order to get a api call. I have set a headers in spring mvc controller as:
#RequestMapping(value = "/admin-api/get-all-order", method = RequestMethod.GET)
public ResponseEntity getAllOrders(#RequestHeader("Authorization") String bearerToken) {
try {
List<OrderModel> order = orderService.getAllOrders();
return new ResponseEntity(order, HttpStatus.OK);
} catch (HibernateException e) {
return new ResponseEntity(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
For requesting api I have used angular 5. I make a api call in angular like:
return this.http.get<T>(this.getAllOrderUrl, {
headers: {
"Authorization": "bearer " + JSON.parse(localStorage.getItem("token"))["value"],
"Content-type": "application/json"
}
}).catch(error => {
return this.auth.handleError(error);
})
But it gave me a strange error.
I have already enabled a CORS for 'localhost:4200'. CORS filtering works fine on other request.
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"X-PINGOTHER,Content-Type,X-Requested-With,Accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Key");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
If I tried in postman it give me a desired result.
Response Header
What am I doing wrong? Please help me out. Hoping for positive response thanks!
If you want to enable CORS without using filters or without config file just add
#CrossOrigin
to the top of your controller and it work.
I'm using spring-web for building a json/rest backend for my web/mobile application.
I was using javax.servlet.Filter, adding appropriate cors header:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, accept, authorization, content-type");
response.setHeader("X-Frame-Options", "SAMEORIGIN");
chain.doFilter(req, res);
}
Now i'm trying to upgrade to spring 4.2.5 and use #CrossOrigin annotation, but it seems that OPTION dispatched response doesn't contains appropriate headers.
Here my configuration:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "it.foo.api.rest", useDefaultFilters = false,
includeFilters = #ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION))
public class WebConfig extends WebMvcConfigurerAdapter {
...
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
// .allowCredentials(true)
// .allowedOrigins("*")
// .maxAge(3600)
// .allowedMethods("PUT", "POST", "GET", "OPTIONS", "DELETE")
// .allowedHeaders("content-type", "authorization", "x-requested-with", "accept", "origin", "Access-Control-Request-Method", "Access-Control-Request-Headers")
// .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials");
// .exposedHeaders("x-requested-with, accept, authorization, content-type");
}
as you can see i've tryed some configurations.
My controller:
#CrossOrigin(allowCredentials="true",
methods={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.OPTIONS,RequestMethod.DELETE},
allowedHeaders={"x-requested-with", "accept", "authorization", "content-type"},
exposedHeaders={"access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options"})
#RestController
#RequestMapping(value="/admin")
public class AdminUserController extends BaseController {
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<AdminUserResource> postLogin(#RequestBody AdminLoginCredentials credentials) {
return new ResponseEntity<AdminUserResource>(..., HttpStatus.OK);
}
Again i've tested with several configuration, with only basic #CrossOrigin annotation.
Headers WITH servlet filter (old version):
Headers WITHOUT filter and WITH #CrossOrigin (new version, not working):
i can't find out what i'm missing!