Apache camel CORS Issue- REST - java

I am having trouble with Apache camel REST API CORS , It is working for GET request but not for other methods.
restConfiguration()
.component("servlet")
.bindingMode(RestBindingMode.auto)
.enableCORS(true)
.corsAllowCredentials(true);
Actual Rest end point implementation
from("rest:post:endpoint1")
//.setHeader("Access-Control-Allow-Credentials",constant( true))
.unmarshal().json(JsonLibrary.Jackson, request.class)
.process(processor);
When adding header to rest request it working for GET request.

You probably need to specify more things, eg
the list of allowed methods
the list of allowed origins
This can be done using adhoc HTTP headers:
.setHeader("Access-Control-Allow-Origin", constant("*") )
.setHeader("Access-Control-Allow-Methods", constant("GET, POST, OPTIONS") )

It is likely not supported by the old Rest component as it is only meant to be used for basic use cases.
For advanced features like CORS, you need to define your rest endpoints using the Rest DSL as next:
rest("/")
.post("/endpoint1").to("direct:endpoint1");
from("direct:endpoint1")
.unmarshal().json(JsonLibrary.Jackson, request.class)
.process(processor);
With the exact same Rest configuration (enableCORS(true)) but with your endpoint defined with the Rest DSL, the CORS HTTP headers will automatically be added to your HTTP responses whatever the HTTP method used.
Here are the HTTP response headers of a POST endpoint defined using the Rest DSL:
curl -v localhost:8080/say -X POST
< HTTP/1.1 200 OK
< Date: Mon, 11 Apr 2022 11:55:57 GMT
< Content-Type: application/json
< Accept: */*
< Access-Control-Allow-Headers: Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
< Access-Control-Allow-Methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
< Access-Control-Allow-Origin: *
< Access-Control-Max-Age: 3600
< User-Agent: curl/7.79.1
< Transfer-Encoding: chunked
< Server: Jetty(9.4.45.v20220203)
Here are the HTTP response headers of a POST endpoint defined using the old Rest component:
curl -v localhost:8080/hello -X POST
< HTTP/1.1 200 OK
< Date: Mon, 11 Apr 2022 11:55:53 GMT
< Accept: */*
< User-Agent: curl/7.79.1
< Transfer-Encoding: chunked
< Server: Jetty(9.4.45.v20220203)

Related

CORS response headers not shown when using #CrossOrigin

I have created a basic GET endpoint, and attempted to allow CORS. However, the expected headers aren't returned in the response body, and I couldn't find what I'm doing wrong here.
GET method in my REST controller:
#CrossOrigin(
allowCredentials = "true",
origins = "*",
allowedHeaders = {
"Access-Control-Allow-Origin",
"Access-Control-Allow-Headers",
"Access-Control-Max-Age",
"Access-Control-Allow-Methods",
"Content-Type"})
public String test() {
return "test";
}
When I send a request here, the response headers are as follows:
Content-Length: 4
Content-Type: text/html;charset=UTF-8
Date: Mon, 13 May 2019 19:33:11 GMT
I'm hoping to add the headers to this response, i.e.:
Content-Length: 4
Content-Type: text/html;charset=UTF-8
Date: Mon, 13 May 2019 19:33:11 GMT
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Max-Age, Access-Control-Allow-Methods, Content-Type
Access-Control-Allow-Origin: *
Any help would be greatly appreciated.
Ahh, I see - these headers are only added for cross-origin requests. When I set the origin in the request headers, the response headers are added as expected.

Spring rest endpoint not returning body

I am very confused about the behavior of one of my rest endpoint int my Spring application
I have a simple controller:
#RestController
public class MyController {
#GetMapping("/test")
public String test(Principal principal) {
System.out.println("HELOOOO");
return "hello";
}
}
And I am sending requests to this endpoint. The request is accepted and returns 200 OK but the body is missing. I see the printline and I see the request being successfully processed in my browser console but there is no body.
I have other endpoints in my application (some even in the same controller class) which work fine so I am confused what might be the reason for this particular one.
EDIT: this is what I am seeing in the web console:
HTTP/1.1 200
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 22 Apr 2019 08:37:46 GMT
Failed to load response data
#ResponseBody annotation does nothing.
EDIT2: Thank you all for your suggestion - especially the one about trying the endpoint with cUrl. The exception was not in Spring but in my client handling the response where I was handling it incorrectly.
You can return a ResponseEntity as following:
#GetMapping("/test")
public ResponseEntity test(Principal principal) {
System.out.println("HELOOOO");
return new ResponseEntity<>("hello", HttpStatus.OK);
}
This worked fine for me.
Response status is an 200, but response ultimately comes with an error message "Failed to load response data".
This could only be due to failure to serialise the data you returned to a valid JSON.
I'm not a Spring expert, but perhaps if you returned "\"hello\"" it should be fine.

Spring Oauth2 CORS issue

I set CORS to allow few custom headers. Below is the Response Header -
Response Headers { "Date": "Mon, 14 Mar 2016 10:11:59 GMT",
"Server": "Apache-Coyote/1.1", "Transfer-Encoding": "chunked",
"Access-Control-Max-Age": "3600", "Access-Control-Allow-Methods":
"POST, GET, OPTIONS, DELETE, PUT", "Content-Type":
"application/json", "Access-Control-Allow-Origin":
"*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers": "X-Requested-With, Authorization,
Content-Type, Authorization_Code, User_Credentials,
Client_Credentials" }
Above response header should mean that API can be consumed from all the origins with following headers: Authorization, Content-Type, Authorization_Code, User_Credentials, Client_Credentials
I can pass all headers and consume APIs from all origins.
PROBLEM -
Requests with Authorization APIs are not being allowed. Authorization is a header with which Oauth token is passed like this - Authorizatio = Bearer ct45tg4g3rf3rfr5freg34gerfgr3gf (Bearer token).
corsclient.js:609 OPTIONS http://54.200.113.97:8080/supafit-api/users
sendRequest # corsclient.js:609(anonymous function) #
corsclient.js:647b.event.dispatch # jquery-1.9.1.min.js:3v.handle #
jquery-1.9.1.min.js:3
/client#?client_method=GET&client_credentials=false&client_headers=Authoriz…nable=true&server_status=200&server_credentials=false&server_tabs=remote:1
XMLHttpRequest cannot load
http://54.200.113.97:8080/supafit-api/users. Response to preflight
request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://client.cors-api.appspot.com' is therefore not
allowed access. The response had HTTP status code 401.
EDIT:
Here is the Rest Client test of that API -
Response Header -
Server: Apache-Coyote/1.1
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Access-Control-Allow-Origin: http://client.cors-api.appspot.com
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Max-Age: 3600
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: X-Requested-With
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Headers: Authorization_Code
Access-Control-Allow-Headers: User_Credentials
Access-Control-Allow-Headers: Client_Credentials
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 14 Mar 2016 11:19:42 GMT Raw JSON
JSON Response Body -
{ "id":78, "userId":"3465434567", "coachId":null,
"name":"XDCDSC", "dob":null, "email":"puneetpandey37#gmail.com",
"imageURL":"https://lh5.googleusercontent.com/-TcTQeitAvag/AAAAAAAAAAI/AAA/4pamurzO1a4/photo.jpg",
"gender":null, "userPhysic":null, "userTypeId":1,
"dietitanId":null, "alternateEmailId":null,
"yearsOfExperience":null, "lastExperience":null,
"languagesKnown":null, "aboutYourself":null,
"coreCompetence":null, "fieldOfWork":null, "userAddresses":[
{
"id":1,
"userId":78,
"locationId":1,
"address":"EC",
"landmark":"Near BN",
"phoneNumber":null,
"addressType":"Home"
} ], "phoneNumbers":[
] }
The response had HTTP status code 401.
Your server needs authentification for the Preflight Request, but the client removes credentials as CORS specification says:
Otherwise, make a preflight request. Fetch the request URL from origin source origin using referrer source as override referrer source with the manual redirect flag and the block cookies flag set, using the method OPTIONS, and with the following additional constraints:
Include an Access-Control-Request-Method header with as header field value the request method (even when that is a simple method).
If author request headers is not empty include an Access-Control-Request-Headers header with as header field value a comma-separated list of the header field names from author request headers in lexicographical order, each converted to ASCII lowercase (even when one or more are a simple header).
Exclude the author request headers.
Exclude user credentials.
Exclude the request entity body.
You have to change your server, to allow anonymous access of Preflight Request.

Analyze HTTP-header before body is transmitted in apache tomcat

Is it possible to analyze the header of a HTTP-(POST)-Request before the body is transmitted?
I would like to send an error to a client if the file he is trying to upload via an HTTP-POST is to large to handle for the server. To improve the user experience (and safe traffic) I would prefer to send the error response before he uploads the whole file, by analyzing the content-length-header.
I thought about implementing a javax.servlet.filter like this:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request.getContentLength() > MAX_DOCUMENT_SIZE) {
ObjectMapper jsonMapper = new ObjectMapper();
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("messageCode", 1234);
jsonMap.put("messageDescription", "error message");
response.reset();
response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
jsonMapper.writeValue(response.getWriter(), jsonMap);
return;
}
}
chain.doFilter(request, response);
}
but I am not sure if the tomcat is able to analyze the headers before the hole request was transmitted.
EDIT: curl
> CONNECT myserver.com:443 HTTP/1.1
> Host: myserver.com:443
> Proxy-Connection: Keep-Alive
> user-agent: my-test
>
< HTTP/1.0 200 Connection established
<
* Proxy replied OK to CONNECT request
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
* Server certificate: myserver.com
> POST /uploads HTTP/1.1
> Host: myserver
> Accept: */*
> user-agent: my-test
> Content-Length: 51951089
> Content-Type: application/x-www-form-urlencoded
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
< HTTP/1.1 404 Not Found
< Date: Tue, 01 Sep 2015 09:49:01 GMT
* Server WEB is not blacklisted
< Server: WEB
< X-XSS-Protection: 1; mode=block
< X-DNS-Prefetch-Control: off
< X-Content-Type-Options: nosniff
< X-Frame-Options: sameorigin
< Strict-Transport-Security: max-age=15768000 ; includeSubDomains
< Cache-Control: private
< Expires: Thu, 01 Jan 1970 01:00:00 GMT
< Content-Type: text/plain;charset=utf-8
< Content-Length: 0
< Vary: Accept-Encoding
< Connection: close
<
Yes, this is possible and I am actually doing this in Tomcat 6. I have not tried a Filter but a Tomcat-specific Valve. If this solution works as a Vavle, feel free to port it to a Filter.
Have Tomcat to invoke your valve. Your demo code looks just the way it should look, make sure that you send a 400 (or better 413) to indicate that the input is not appropriate. You may close the connection too. Now here comes the very important part: to make this work, the client has to POST or PUT the request, additionally the client must send a Expect: 100-continue header. The server will analyze all incoming headers and signal the client that the request is inappropriate. With that, the client will receive a 400 (or better 413) before it sends off its payload (request will be aborted). You'll exchange headers only and save resources. But beware, your clients must properly implement Expect: 100-continue. .NET clients don't. I would strongly recommend to verify the proper working of your valve with curl because it does the stuff right. If you'd like to see wire headers for this, no problem.
Caveat: your content length limit won't work if the client streams its payload in chunks.
You write a java script function and bind it onchange event on input type="file" files[0].size will give u size of the file.So u can check if it is uploadable.
Thx

App Engine HTTP Status Code message

I found an inconsistency between Java's dev_appserver and the live App Engine server.
On my local development server I have a Servlet which returns:
return response.sendError(response.SC_BAD_REQUEST, "Please log in to comment");
When I access the page I get back a Status Code message in the header which is:
Status Code:400 Please log in to comment
The issue comes when I deploy this to App Engine. When accessing that same servlet I get this "Bad Request" instead of "Please log in to comment":
Status Code:400 Bad Request
The Please log in to comment Status Code message appears in the content HTML, but not in the header as it does in the development environment.
Why is this?
Edit
Here's the curl -vvvv traces for both dev_appserver and production:
dev_appserver curl trace:
> POST /add-comment HTTP/1.1
> User-Agent: Mozilla/4.0
> Host: localhost:8080
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 400 Please log in to comment
< Content-Type: text/html; charset=iso-8859-1
< Cache-Control: must-revalidate,no-cache,no-store
< Content-Length: 1406
< Server: Jetty(6.1.x)
Production curl trace:
> POST /add-comment HTTP/1.1
> User-Agent: Mozilla/4.0
> Host: www.xxx.org
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 400 Bad Request
< Content-Type: text/html; charset=utf-8
< Vary: Accept-Encoding
< Date: Thu, 18 Aug 2011 14:04:26 GMT
< Server: Google Frontend
< Cache-Control: private
< Transfer-Encoding: chunked
I would say the prod system is the correct implementation. The javadocs for sendError() say:
Sends an error response to the client using the specified status. The
server defaults to creating the response to look like an
HTML-formatted server error page containing the specified message,
setting the content type to "text/html", leaving cookies and other
headers unmodified. If an error-page declaration has been made for the
web application corresponding to the status code passed in, it will be
served back in preference to the suggested msg parameter.
If the response has already been committed, this method throws an
IllegalStateException. After using this method, the response should be
considered to be committed and should not be written to.
I highlighted a part. This says it just returns a html page with the message when possible. It doesn't say it uses it in the HTTP Status code (which I personally haven't seen anywhere as well :()
It isn't specifically a problem with sendError. The setStatus method will behave the same way. Under normal Java, both sendError and setStatus do set the status description. The issue is that the production App Engine server always sets the status description to the standard description for each code.

Categories