While trying to access RedHat BRMS kie server, i am not able to use POST/PUT methods through rest client - drools

Trying to access POST data through rest client, getting 405.
The response headers states Allow: GET, OPTIONS, HEAD.
So how can I make my rest container accept POST/PUT methods?
EndPoint http://localhost:8080/kie-server/services/rest/server Request Headers used -
Content-Type: application/json
authorization: Basic !#$#%&$$(((
Accept: application/json
X-KIE-ContentType: JSON RESPONSE HEADERS
Server: Apache-Coyote/1.1
Allow: GET, OPTIONS, HEAD
Content-Type: text/html;charset=utf-8
Content-Length: 1088
Date: Thu, 01 Sep 2016 08:43:33 GMT
Tried using Advanced rest client,curl and java code but Same results :(
Referred - https://access.redhat.com/documentation/en-US/Red_Hat_JBoss_BRMS/6.3/html/Getting_Started_Guide/chap-Hello_World_rule_example.html

I think you have to change the Endpoint (URL). I would suggest
http://localhost:8080/kie-server/services/rest/server/containers/instances/("nameOfYourDeployment")
Or try without instances.

In Rest Client provide the following set of values:
URL:
http://localhost:8080/kie-server/services/rest/server/containers/instances/<name-of-your-container>
HEADER:
Accept: application/json
Content-Type: application/json
select method type POST and your JSON request payload
When you hit the API it will ask you for the username and password provide the credentials.
fou can send
payload
as:
{
"commands": [
{
"insert": {
"out-identifier": "Input",
"return-object": "true",
"object": {
"<complete-package-name>.<class-name>": {
"variable-1" : "value-1",
"variable-2" : "value-2"
}
}
}
},
{
"fire-all-rules": {
"outIdentifier": "output"
}
}
]
}

Related

Axios doesn't initiate POST request

I am using webdriverIO version 7 and axios in order to try to make login via API instead of doing it using UI.
This is my code:
getAuthToken({ email, password }) {
// axios
// .post('https://my-app.com/login', {
// j_username: email,
// j_password: password,
// CSRFToken: 'some-token',
// })
// .then((response) => {
// console.log('XXX');
// console.log(response);
// });
const data = {
j_username: email,
j_password: password,
CSRFToken: 'some-token',
};
axios({
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url: 'https://my-app.com/login',
}).then((response) => {
console.log('XXX');
console.log(response);
});
}
I am trying to do it in both ways as above but I don't get ever response printed in the console.
I tried to do the request via Postman and it is working fine.
Also I am monitoring the traffic on the site via Fiddler Everywhere app and when this method gets executed, then nothing is shown in the Fiddler.
On the other hand when I do it via Postman, Fiddler catches it.
This is Raw Postman Request data:
POST https://my-app.com/j_spring_security_check HTTP/1.1
User-Agent: PostmanRuntime/7.28.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 39311680-b11c-4a65-8ff7-2f03b97bf5eb
Host: my-app.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------619522728182415185770824
Cookie: anonymous-consents=%5B%5D; cookie-notification=NOT_ACCEPTED
Content-Length: 436
----------------------------619522728182415185770824
Content-Disposition: form-data; name="j_username"
email#test.com
----------------------------619522728182415185770824
Content-Disposition: form-data; name="j_password"
123456
----------------------------619522728182415185770824
Content-Disposition: form-data; name="CSRFToken"
some-token
----------------------------619522728182415185770824--
This is Raw Request when I do it through Chrome
POST https://my-app.com/j_spring_security_check HTTP/1.1
Host: my-app.com
Connection: keep-alive
Content-Length: 90
Cache-Control: max-age=0
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"
sec-ch-ua-mobile: ?0
Upgrade-Insecure-Requests: 1
Origin: https://my-app.com
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://my-app.com/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=some_id; dtCookie=some_data; anonymous-consents=%5B%5D; cookie-notification=NOT_ACCEPTED
j_username=ecx%40test.com&j_password=123456&CSRFToken=some_token
What am I doing wrong? Why it doesn't never log the response while doing it through axios?
Thanks!
The function is written correctly.
Postman passes additional details also which you can to look into.
Lets consider the scenarios which may cause the API call to fail:
Your function might not be correct.
The API is not configured properly.
Issues in the network.
Tackling the first scenario:
Check whether the function getAuthtoken() is getting invoked or not.
There might be an issue of CORS which you need to fix.
As you are send a JSON data, the server side must also accept the JSON data, or specify it in request headers. like
const data = {"name":"Example"}
axios.post('https://linkToApI.com', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'some_auth_method_like_authToken',
specify other necessary headers
},
data
})
Getting to the second scenario:
Configuring the server is important.
make sure there is not any cors issue which is getting in the way.
make sure server is accepting the request data which you are sending.
make sure if the request fails it sends a error response.
Additional changes in the code for debugging purposes:
Whatever code you use please try to add a catch block as if the promise fails we can get the error message why is it failing. below is the example:
axios({
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url: 'https://my-app.com/login',
}).then((response) => {
console.log('XXX');
console.log(response);
}).catch(e=>{console.log(e)}); // this will provide you with info why is it failing

API Gate away Is Blocked even when CORS is enabled

I'm trying to make an api to upload images to cloudinary like this
fd.append('photos', file);
fd.append('upload_preset',
CLOUDINARY_UPLOAD_PRESET);
axios({
url: CLOUDINARY_API,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Headers': 'Origin',
'Access-Control-Allow-Credentials': true
},
data: fd
}).then(function(res) {
console.log(res);
}).catch(function(err) {
console.error(err);
})
})
but i recieve this error from the browser
Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/******/mh/upload' from origin 'http://127.0.0.1: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.Blockquote
You will need to remove the three "Access-Control-Allow-*" headers from the request you are sending.
The headers Cloudinary allows for cross-origin requests don't include those headers which you are sending and therefore the browser throws this error.
Below are the headers that are allowed for cross-origin uploads (under Access-Control-Allow-Headers):
curl -sD - -X OPTIONS https://api.cloudinary.com/v1_1/demo/image/upload
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Cache-Control, Content-Disposition, Content-MD5, Content-Range, Content-Type, DPR, Viewport-Width, X-CSRF-Token, X-Prototype-Version, X-Requested-With, X-Unique-Upload-Id
Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS
Access-Control-Max-Age: 1728000
Cache-Control: no-cache
Content-Type: text/plain; charset=utf-8
Date: Sat, 19 Dec 2020 09:49:48 GMT
Server: cloudinary
Status: 200 OK
Vary: Accept-Encoding
X-Request-Id: d1af2a2f8a986d9ebbd1f14399dd409d
X-UA-Compatible: IE=Edge,chrome=1
X-XSS-Protection: 1; mode=block
Content-Length: 0
Connection: keep-alive
EDIT: In addition, Cloudinary API doesn't have a parameter called "photos". The file to upload is sent in the "file" parameter.
Therefore, you would need to replace fd.append('photos', file); with fd.append('file', file);.

(questions about POST requests) Is there a way to send a POST request and then get back the retrieved resource in the event of a 302 externally?

This is a bit confusing but I'm going to try my best to explain it properly, I'll really appreciate an answer to this.
Suppose I've got the endpoint "example.com/login" that displays an HTML page with a login form that upon submitting sends a POST request to "example.com/login" (yes itself) with the credentials (shown below) and then upon successful authentication displays another HTML page (example.com/user/records) that shows your details (for e.g your data records and stuff).
What I plan on doing is accessing the HTML page that shows that data by sending a POST request externally using Javascript with the credentials and then somehow just receiving the HTML for the data records page as a string response as we'd normally get through a GET request (is this even possible?).
upon sending said request it shows this in the network tab:
(Remote Address has been modified to replace all numbers with 0)
Request URL: https://example.com/login
Request Method: POST
Status Code: 302
Remote Address: 000.000.000.000:000
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
cache-control: no-store, no-cache, must-revalidate
content-type: text/html; charset=UTF-8
date: Mon, 30 Nov 2020 22:43:08 GMT
expires: Thu, 19 Nov 1981 08:52:00 GMT
location: https://example.com/user/records
pragma: no-cache
server: Apache
Request Headers:
:authority: example.com
:method: POST
:path: /login
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: en
cache-control: max-age=0
content-length: 47
content-type: application/x-www-form-urlencoded
cookie: roundcube_cookies=enabled; timezone=Asia/Baghdad; resetpasscookie=kUcAf8R5ue5VsOVM; webmailsession=%3af5nnuvNuUHvJaAWn%2c73236ca3fe2776acd45d97c7fffdfd79; whostmgrsession=%3alTiPVRgz7acX0SQG%2c97f0382efe30423a72f3caefec64192f; cpsession=%3arm4IkcjwHaihjbFR%2c859b30622f8d57aebed715dea4d2791e; ci_session=2vofur1iqi6sgrurb1s2dtb5f0tfggi8
origin: https://example.com
referer: https://example.com/login
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36
Form Data:
ci_csrf_token:
username: abc
password: 123
first concern: Where on Earth did those cookies even come from?? (if they're set by the server then is there a way I can still do what I plan on doing?)
I just copied that request from the options directly as a Node fetch request and ran it in Visual Studio Code externally (not connected to that website in any way right now) and got this:
(an account with details username: abc, password: 123 exists suppose - I've just replaced the credentials)
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kTransformState)]: [Object]
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://example.com/login',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 2
}
} Headers {
[Symbol(map)]: [Object: null prototype] {
date: [ 'Mon, 30 Nov 2020 22:54:12 GMT' ],
server: [ 'Apache' ],
expires: [ 'Thu, 19 Nov 1981 08:52:00 GMT' ],
'cache-control': [ 'no-store, no-cache, must-revalidate' ],
pragma: [ 'no-cache' ],
'set-cookie': [
'ci_session=06ujfc27fpp73a01nia1dp3pehsskep5; expires=Tue, 01-Dec-2020 00:54:12 GMT; Max-Age=7200; path=/; HttpOnly'
],
upgrade: [ 'h2,h2c' ],
connection: [ 'Upgrade, close' ],
'transfer-encoding': [ 'chunked' ],
'content-type': [ 'text/html; charset=UTF-8' ]
}
}
2nd concern) Why was I greeted with code 200 here, and 302 on the browser?
Anyways, I planned on authenticating myself by copying the post request that would've been sent through the login form and supplying various correct credentials so I could access their details using Javascript externally, and then manipulate them.
If this can't work then is there any other way to do this? Or if it can, then how?
I realized it could be solved in some cases by providing {"redirect": "follow"} to the options when using fetch.

User storage is cleared when prompting for required parameter

I have a simple Welcome intent that contains a single required parameter. I am also using user storage to store a GUID for the current user, so they can come back and resume the conversation at a later stage.
This works fine if my Welcome intent doesn't contain a required parameter, i.e. the user can stop the conversation and come back much later, invoke the action again, and the user storage is still there.
But with the required parameter, the question that prompts for the value of that parameter appears to clear the user storage, so I no longer recognise the user. Is this expected/ how do I work around this (without using account linking)?
This is from the logs:
the initial invocation still contains the user storage values:
Sending request with post data: {"user":{"locale":"en-US","lastSeen":"2019-08-09T13:25:39Z","userStorage":"{\"data\":{\"userId\":\"23676205-5964-158d-44d0-c949ea01f6cc\"}}","userVerificationStatus":"VERIFIED"},"conversation":{"conversationId":"ABwppHG4dZXBOH0w3hbA8diwssTMi0z6uXvNcvzYFlJgAXW0ShoxhAQolhCP9Zq1TRxW8NxRyAl0V6GEDdrrLCMUkZST","type":"NEW"},"inputs":[{"intent":"actions.intent.MAIN","rawInputs":[{"inputType":"KEYBOARD","query":"Talk to IPSOS Diary Demo"}]}],"surface":{"capabilities":[{"name":"actions.capability.SCREEN_OUTPUT"},{"name":"actions.capability.MEDIA_RESPONSE_AUDIO"},{"name":"actions.capability.ACCOUNT_LINKING"},{"name":"actions.capability.AUDIO_OUTPUT"},{"name":"actions.capability.WEB_BROWSER"}]},"isInSandbox":true,"availableSurfaces":[{"capabilities":[{"name":"actions.capability.WEB_BROWSER"},{"name":"actions.capability.AUDIO_OUTPUT"},{"name":"actions.capability.SCREEN_OUTPUT"}]}],"requestType":"SIMULATOR"}.
the agent then sends back one of the prompt questions defined for the required parameter in the welcome intent:
Received response from agent with body: HTTP/1.1 200 OK Server: nginx/1.13.6 Date: Fri, 09 Aug 2019 13:25:48 GMT Content-Type: application/json; charset=utf-8 X-Content-Type-Options: nosniff google-actions-api-version: 2 Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: Mon, 01 Jan 1990 00:00:00 GMT P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info." Content-Security-Policy: script-src 'report-sample' 'nonce-B8FmozDlPwPnGpgtItuU8A' 'unsafe-inline';object-src 'none';base-uri 'self';report-uri /_/DialogflowRuntimeAogHttp/cspreport;worker-src 'self' Content-Encoding: gzip X-XSS-Protection: 0 X-Frame-Options: SAMEORIGIN Set-Cookie: NID=188=wmvmHPvwa5ROoJQ5xNgLzzXmo4qPq4yyAX44A2ix7o0Vy2mgwiKJT92Th8KQtmz2YNBJWdx7W4pT_v610J-y1LRKig-NqHcpqJp8uLk84L-fnqBn2m7HIfvUlMDwb-SnwakZmcPu6SRKBBsS_FcXINYZ83ydJToyY-df3CxBAfg; expires=Sat, 08-Feb-2020 13:25:48 GMT; path=/; domain=.google.com; HttpOnly Via: 1.1 google Alt-Svc: clear Transfer-Encoding: chunked { "conversationToken": "[\"e8b7f358-3964-477c-a161-11da9d90e6bb_id_dialog_context\",\"default_welcome_intent_dialog_context\",\"default_welcome_intent_dialog_params_surveyname\",\"actions_capability_screen_output\",\"actions_capability_media_response_audio\",\"actions_capability_account_linking\",\"actions_capability_audio_output\",\"actions_capability_web_browser\",\"google_assistant_input_type_keyboard\",\"google_assistant_welcome\"]", "expectUserResponse": true, "expectedInputs": [{ "inputPrompt": { "richInitialPrompt": { "items": [{ "simpleResponse": { "textToSpeech": "Which survey is it?", "displayText": "Which survey is it?" } }] } }, "possibleIntents": [{ "intent": "assistant.intent.action.TEXT" }], "speechBiasingHints": ["$surveyname", "$surveyname"] }], "responseMetadata": { "status": { "message": "Success (200)" }, "queryMatchInfo": { "intent": "e8b7f358-3964-477c-a161-11da9d90e6bb" } }, "expectedInput": { "requestedIntent": { "intent": "e8b7f358-3964-477c-a161-11da9d90e6bb", "parameterName": "surveyname" } } }.
but when I get the response to the above prompt question, the user storage is now non-existent:
Sending request with post data: {"user":{"locale":"en-US","lastSeen":"2019-08-09T13:25:39Z","userVerificationStatus":"VERIFIED"},"conversation":{"conversationId":"ABwppHG4dZXBOH0w3hbA8diwssTMi0z6uXvNcvzYFlJgAXW0ShoxhAQolhCP9Zq1TRxW8NxRyAl0V6GEDdrrLCMUkZST","type":"ACTIVE","conversationToken":"[\"e8b7f358-3964-477c-a161-11da9d90e6bb_id_dialog_context\",\"default_welcome_intent_dialog_context\",\"default_welcome_intent_dialog_params_surveyname\",\"actions_capability_screen_output\",\"actions_capability_media_response_audio\",\"actions_capability_account_linking\",\"actions_capability_audio_output\",\"actions_capability_web_browser\",\"google_assistant_input_type_keyboard\",\"google_assistant_welcome\"]"},"inputs":[{"intent":"actions.intent.TEXT","rawInputs":[{"inputType":"KEYBOARD","query":"baby diary"}],"arguments":[{"name":"text","rawText":"baby diary","textValue":"baby diary"}]}],"surface":{"capabilities":[{"name":"actions.capability.SCREEN_OUTPUT"},{"name":"actions.capability.MEDIA_RESPONSE_AUDIO"},{"name":"actions.capability.WEB_BROWSER"},{"name":"actions.capability.AUDIO_OUTPUT"},{"name":"actions.capability.ACCOUNT_LINKING"}]},"isInSandbox":true,"availableSurfaces":[{"capabilities":[{"name":"actions.capability.SCREEN_OUTPUT"},{"name":"actions.capability.WEB_BROWSER"},{"name":"actions.capability.AUDIO_OUTPUT"}]}],"requestType":"SIMULATOR"}.

What is a correct RESTful service response to a PUT request on successful update?

What is a correct RESTful service response to a PUT request on successful update?
There are two possible responses that seem to comply with REST architectural style:
Return only a header without body with the status 204.
Header:
content-type: application/json; charset=utf-8
status: 204 No Content
ratelimit-limit: 5000
ratelimit-remaining: 4816
ratelimit-reset: 1444931833
Return a header with the status 200 and a body that contains the actual representation of an entity after an update.
Header:
content-type: application/json; charset=utf-8
status: 200 OK
ratelimit-limit: 5000
ratelimit-remaining: 4816
ratelimit-reset: 1444931833
Body:
{
"foo": "bar",
"baz": "qux"
}
If your response includes returned data then its status should be 200, otherwise 204.