I have a restlet resource that authenticates a person and sets a cookie with a key:
#Post("json")
public Representation login(String json) {
// validate user credentials ...
getResponse().getCookieSettings().add(new CookieSetting(1, "k", key));
getResponse().getCookieSettings().add(new CookieSetting(1, "p", person.getURI()));
return new StringRepresentation(response.toString(), MediaType.APPLICATION_JSON);
}
When I invoke the URL associated with the login() method, everything seems to be fine. The cookies seem to be returned correctly in the response, and if I already have received cookies before, they are sent to the server:
Remote Address: 127.0.0.1:8000
Request URL: http://127.0.0.1:8000/api/person
Request Method: POST
Status Code: 200 OK
Request Headers
Accept: undefined
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,pt-PT;q=0.6,pt;q=0.4,es-419;q=0.2,es;q=0.2,en-GB;q=0.2
Connection: keep-alive
Content-Length: 42
Content-Type: application/json
Cookie: k="546f71445bf1bacd60a3f715d0250267"; p="http://compflow.pt/flowOntology/admin"
Host: 127.0.0.1:8000
Origin: http://127.0.0.1:8000
Referer: http://127.0.0.1:8000/job
X-Requested-With: XMLHttpRequest
Response Headers
Accept-Ranges: bytes
Content-Length: 46
Content-Type: application/json; charset=UTF-8
Date: Tue, 01 Jul 2014 15:05:13 GMT
Server: Restlet-Framework/2.1.7
Set-Cookie: k=546f71445bf1bacd60a3f715d0250267
Set-Cookie: p=http://compflow.pt/flowOntology/admin
Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
The invocation to http://127.0.0.1:8000/api/person is performed through an AJAX call using JQuery as follows:
$.ajax({
url: '/api/person',
type:'POST',
accepts : "application/json",
contentType : "application/json",
processData : false,
dataType : "text",
data: JSON.stringify(data),
success: function (data) {
data = JSON.parse(data);
sessionStorage["userData"] = JSON.stringify(data.data);
if(callback) callback();
},
error: function(data) {
$('.alert-error').text(data).show();
}
});
However, if I try to perform a GET (directly through the browser) to the address http://127.0.0.1:8000/job, the cookies are not sent. The Cookie header is not set in the request.
Since it is not a cross-domain request and no restrictions are set regarding the path and domain of the cookies (I have tried setting them to "/" and "127.0.0.1" to no avail), I have no ideas left regarding what may be causing this issue. I would greatly appreciate all the help you can give me.
Curiously, the kind of HTTP server connector changes the behavior of the code. I've entered an issue for that (https://github.com/restlet/restlet-framework-java/issues/927).
As a workaround, I suggest you to precise the path, as follow:
getCookieSettings().add(new CookieSetting(0, "k", key, "/", null));
NB: inside a ServerResource; you can use the shortcut "getCookieSettings()", instead of "getResponse().getCookieSettings()".
Related
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.
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.
I'm able to get Credentials using AuthorizationCodeFlow in Java running in Tomcat.
Now I'm trying to pass the access token I get on the server back to the client so that we are able to use gapi javascript client to do work in the browser without having to go through our server.
I set the access token in gapi using the following:
function setAccessToken() {
gapi.auth.setToken({
access_token: '<access_token from server>'
});
}
I then call the gapi.client.load to get the drive client code:
gapi.client.load('drive', 'v2', onDriveClientLoaded);
I then call a function to get or create a folder in Google Drive (This has been tested using gapi.auth.authorize(), so I know the code as it is should work.).
function onDriveClientLoaded() {
getOrCreateFolder();
}
But in getOrCreateFolder when I make a call to gapi.client.drive.children.list(...) the response is
{
code: 401,
message: "Invalid Credentials",
...
}
I've seen multiple places where people indicate that they have done this. But so far I cannot get this working.
In fiddler I am getting the following response:
HTTP/1.1 401 Unauthorized
Vary: Origin
Vary: X-Origin
WWW-Authenticate: Bearer realm="https://accounts.google.com/", error=invalid_token
Content-Type: application/json; charset=UTF-8
Date: Fri, 01 May 2015 20:16:22 GMT
Expires: Fri, 01 May 2015 20:16:22 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alternate-Protocol: 443:quic,p=1
Content-Length: 249
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Here is the slightly edited request:
GET https://content.googleapis.com/drive/v2/files/root/children?q=title%20%3D%20%27TestFolder%27 HTTP/1.1
Host: content.googleapis.com
Connection: keep-alive
Authorization: Bearer <access_token from server>
X-Goog-Encode-Response-If-Executable: base64
X-Origin: http://localhost:8080
X-ClientDetails: appVersion=5.0%20(Windows%20NT%206.1)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F42.0.2311.90%20Safari%2F537.36&platform=Win32&userAgent=Mozilla%2F5.0%20(Windows%20NT%206.1)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F42.0.2311.90%20Safari%2F537.36
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
X-JavaScript-User-Agent: google-api-javascript-client/1.1.0-beta
X-Referer: http://localhost:8080
Accept: */*
X-Chrome-UMA-Enabled: 1
X-Client-Data: CKu1yQEIhLbJAQijtskBCKm2yQEIxLbJAQiiicoBCImSygE=
Referer: https://content.googleapis.com/static/proxy.html?jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.OuOrzZ8GQcU.O%2Fm%3D__features__%2Fam%3DIQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCO9uGNmv6wlfXBJwCbYRCdcqx94WQ
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
If-None-Match: "dM4Z0GasI3ekQlrgb3F8B4ytx24/sCBysa-CxrZGnYdsTvea7yHHhJ0"
Turns out everything is working as expected.
I need to look at the refresh of tokens, as the access_token I was using was not valid, hence the "Invalid Credentials" message.
I tested the access_token by putting the following in postman:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<access_token>
When using the incorrect access_token I was getting the invalid credentials response, but when I refreshed the token I got the following valid response:
{
"issued_to": "<some_id>.apps.googleusercontent.com",
"audience": "<some_id>.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/drive",
"expires_in": 3470,
"access_type": "offline"
}
I have developed a raw http post in java. I am trying to post a file to the post request dump website http://www.posttestserver.com/. But it shows and error
400 Bad Request. Pleas let me know what need to be done to avoid this error.
In this code , output => Stream to write on server.
filename -> path on server, here filename is initated to post.php
output.println("POST"+" "+filename+" HTTP/1.1\r");
//output.println("Content-Length: "+data.length());
output.println("Content-Type: multipart/form-data, boundary=AaB03x\r");
output.println("Content-length: 100\r");
//As http1.1 is by default keep-alive , close the connection explicitly
output.println("Connection: Close");
// blank line
output.println();
output.println("--AaB03x");
output.print(
"--AaB03x Content-Disposition: form-data; name=\"fileID\"; filename=\"temp.txt\" Content-Type: text/plain "
+"/nHello How are you?"
+ "/n--AaB03x--");
output.flush();
Error is
HTTP/1.1 400 Bad Request
Date: Wed, 18 Mar 2015 02:22:00 GMT
Server: Apache
Vary: Accept-Encoding
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1
400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.
This might be the issue of Content type. Server is expecting a request having header of content type text/HTML but your request content type is multipart/form data.
I have a web application that use Angularjs on frontend och Resteasy + Jackson on the back end. I'm sending a file from Angular component to a REST method, receiving method looks like this :
#POST
#Path("/upload/attachment/for/{eventId}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(MultipartFormDataInput input,
final #PathParam("eventId") Long eventId,
#Context HttpServletRequest request) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
...my awesome stuff...
return Response.ok().build();
}
And request has following headers when sent :
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length 347085
Content-Type multipart/form-data; boundary=---------------------------12164806981346771846716776342
Cookie JSESSIONID=aoBd1hgzR3GM8bSG5P-9g-vQ; csrftoken=ziQ7kN7TlMehR2aURDrmaMLYAroMsSpu
Host localhost:9000
Referer http://localhost:9000/local/myapp/index.html
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:32.0) Gecko/20100101 Firefox/32.0
The problem is that THIS request ALWAYS has application/json as a Content-Type instead for multipart/form-data as it says in the headers. And I get :
20:12:00,490 WARN [org.jboss.resteasy.core.SynchronousDispatcher] (http-/127.0.0.1:8080-2) Failed executing POST /events/upload/attachment/for/null: org.jboss.resteasy.spi.UnsupportedMediaTypeException: Cannot consume content type
Already in HttpServletDispatcher the content is wrong.
I can't get if this is JBOSS that set Content-Type to wrong value or some thing else.
Ok, it was that I have an extra layer between angular and server which runs on Node.js and it just tunel requests to the server. I had to add following :
var r = null;
r = request.put({uri: url, json: inReq.body, headers: inReq.headers, form: inReq.form});
inReq.pipe(r).pipe(inRes);
This set all the headers from outgoing request and tunnel the request
Now I have right content-type