How to get the set-cookie from http response that is set by server using express.js? - express

For the cookie that is attached to http request we use "req.headers.cookie". Just like that I want to be able to console log the set-cookie value.
Currently I'm using "res._headers" which logs
[Object: null prototype] {
'x-powered-by': 'Express',
location: 'secrets',
vary: 'Accept',
'content-type': 'text/html; charset=utf-8',
'content-length': '58',
'set-cookie': [
'connect.sid=s%3A0nacHXK6fTKoQwBsVNvjW659OltdoVMR.L38W5Exjqg7wHnx70MF8OQu05uOFzWrrxJCgZ41RX7o; Path=/; HttpOnly'
]
But how can I just log the connect.sid(set-cookie) value?
Tried: res._headers"

Related

Directus api create item works but data values are null

Using Directus online (https://projectcode.directus.app install of local or server install). I can successfully create item but data I send is always null.
This is happening running my code
axios.post(
`${endpoint}/items/collection_name`,
{ data: { "field_name": "testthis" } },
{ headers: headers }
);
And using Postman. Result is always
date_created: "2022-05-05T13:55:47"
id: 14
field_name: null
I can get items, search and filter with no issue. What am I missing?
ETA: Postman works with graphql and query
mutation {
create_collection_name_item(data: { field_name: "Hello again!" }) {
field_name
}
}
So why is api getting null values?
ETA 2: Postman api headers
Request
Authorization: Bearer the_very_long_token
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 45943ddb-5c60-4d45-8887-a05207f9469e
Host: k2g2xa7b.directus.app
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
Response
Content-Type: application/json; charset=utf-8
Content-Length: 135
Connection: keep-alive
Date: Mon, 09 May 2022 14:04:54 GMT
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Content-Range
Cache-Control: no-cache
Content-Security-Policy: script-src 'self' 'unsafe-eval';worker-src 'self' blob:;child-src 'self' blob:;img-src 'self' data: blob: https://cdn.directus.io;media-src 'self' https://cdn.directus.io;connect-src 'self' https://*;default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';object-src 'none';script-src-attr 'none';style-src 'self' https: 'unsafe-inline'
Etag: W/"87-n/ABsgX1O7F1qQ7x0xdJgMV7VDc"
Server: Caddy
Vary: Origin, Cache-Control
X-Powered-By: Directus
X-Cache: Miss from cloudfront
Via: 1.1 dcd16c430149132ea12a5783d54ff114.cloudfront.net (CloudFront)
X-Amz-Cf-Pop: YTO50-P2
X-Amz-Cf-Id: Z19onMWqxvINuZ7iMQIJQeSRFrgW12a4gxZtcWPyubaWQCeaUnfLfA==
What headers do you provide? It seems that Content-Type is not determined automatically, so it may be as simple as including Content-Type: application/json in your headers.
in python:
import requests, json
token = 'your token'
headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.5',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
'Content-Type': 'application/json',
'Authorization': f"Bearer {token}",
}
payload = [
{
"title" : "my first item",
}
]
r= requests.post(
url = "https://cms.uat.<your subdomain>.com/items/<your collection>",
data = json.dumps(payload),
headers = headers
)
print(r.json())

Cant get local Api call work with Vue and Codeigniter

My wish: Making api calls on my local develoment environment.
My Problem: i use Headers for authorization, but my custom header is never seen in my api so the response is always 403 forbidden.
I'm new to creating Vue apps i've used the Vue CLI to create a local develop environment running on http://localhost:8080/ via npm run serve
Next to this ive created an own API with codeigniter (v2) its a simple straight forward api with 1 controller handling a couple of requests. I'm running this API on a local MAMP installation. with Url http://apiname.myname.local.
In Vue ive used mounted to start the API call. Ive tried this with axios, fetch, XMLHttpRequest and superagent. None of these seem to work.
In the MAMP apache config (httpd.conf) ive added this:
`< Directory />
Options Includes
AllowOverride All
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "authorization, Content-Type, X-Auth-Token,
Origin, Authorization, X-Auth-Token, x-auth-token"
< /Directory>`
And also this variant:
`< Directory />
Options Includes
AllowOverride All
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "*"
Header always set Access-Control-Allow-Headers "*"
< /Directory>`
In the Codeigniter Controller contructor ive added this:
`header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: x-auth-token, X-Auth-Token, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");`
And also this variant:
`header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");`
In the vue app ive tried these:
`axios({
method: 'get',
headers: {
'Authorization': 'Whatever',
'X-Auth-Token': 'Whatever'
},
url: 'local_api_url'
}).finally(function () {
alert("ja");
});`
Or this (tried with and without the cors option. and with and without the credentials option.
`fetch('local_api_url',{
method: 'GET',
mode: 'no-cors',
headers: {
'Authorization': 'Whatever',
'X-Auth-Token': 'Whatever',
}
})`
Or this
`var x = new XMLHttpRequest();
x.open("GET","local_api_url");
x.setRequestHeader("Authorization","Whatever");
x.setRequestHeader("X-Auth-Token","Whatever");
x.send();`
None work.
Also in the Chrome Dev tools it looks like the header is never added to the request (well i think so) When i open the request in the network tab and click the tab Headers these are the Request Headers.
`Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: nl,de-DE;q=0.9,de;q=0.8,nl-NL;q=0.7,en-US;q=0.6,en;q=0.5
Access-Control-Request-Headers: authorization,x-auth-token
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: local_api_url
Origin: http://localhost:8080
Pragma: no-cache
Referer: http://localhost:8080/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36`
And the response headers:
`Access-Control-Allow-Headers: authorization, Content-Type, X-Auth-Token, Origin, Authorization, X-Auth-Token, x-auth-token
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
Date: Fri, 06 Dec 2019 10:52:20 GMT
Keep-Alive: timeout=5, max=100
Server: Apache
Set-Cookie: ci_session_blabla
Set-Cookie: ci_session_blabla
Set-Cookie: ci_session_blabla
Set-Cookie: ci_session_blabla
Set-Cookie: ci_session_blabla
Set-Cookie: ci_session_blabla
Transfer-Encoding: chunked
X-Powered-By: PHP/7.2.14`
Ive also tried all this with a Vue proxy by creating a vue.config.js with this content:
`module.exports = {
devServer: {
proxy: 'local_api_url'
}
}`
Im using this code in Codeigniter to het the headers.
`$headers1 = getallheaders();
$headers2 = $this->input->request_headers();
$header_present = array_key_exists('X-Auth-Token', $headers);`
Whatever ive tried, also different combinations of the above, $header_present is always False!
So basically i think ive tried all solutions presented in other topics (and other sites like Github) and now ive no idea how to fix this and seriously consider to do authentication trough the body of the request instead of the header. Can someone help me?
Ive got the following working: in MAMP ive added this to the httpd.conf:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
now ive used this code in my app:
axios({
method: 'GET',
url: 'loal_api_url',
headers: {
'Authorization': 'Bearer api_key'
}
})
This seems to work, im receiving the Authorization header now in my API. But im receiving 2 requests and the Authorization header is only filled in the second request.
For now ive used the following code in my API to only check the Authorization when:
if ($_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
if (!array_key_exists('Authorization', $headers){
ALLOW REQUEST
}
}
And also in my data response:
$return = "OKAY";
if ($_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
$return = $retval;
}
http_response_code(200);
header('Content-type: application/json');
die(json_encode($return));

Box api call returning 403 forbidden error in Vue but the same URL working in postman

I have a developer token for box and the box app all set up. when I use Postman I get the data that I am looking for returned. I have looked at the headers that Postman is sending and have provided the same in my code.
axios({
async: true,
crossDomain: true,
url: 'https://api.box.com/2.0/files/<File ID>/',
method: 'GET',
headers: {
'Postman-Token': '<Postman Token>',
'cache-control': 'no-cache',
Authorization: 'Bearer <Developer Token>',
Accept: '*/*',
},
}).then((res) => {
console.log(res);
}).catch(console.error);
This returns a 403 in the browser.
This is the Response Headers from Postman:
Date:"Wed, 03 Apr 2019 06:04:45 GMT"
Content-Type:"application/json"
Transfer-Encoding:"chunked"
Connection:"keep-alive"
Strict-Transport-Security:"max-age=31536000"
Cache-Control:"no-cache, no-store"
ETag:""0""
Content-Encoding:"gzip"
Vary:"Accept-Encoding"
BOX-REQUEST-ID:"<BOX-REQUEST-ID>"
Age:"0"
Response Headers from bowser
Access-Control-Allow-Origin: *
Age: 0
BOX-REQUEST-ID: <BOX-REQUEST-ID>
Cache-Control: no-cache, no-store
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json
Date: Wed, 03 Apr 2019 06:36:01 GMT
Strict-Transport-Security: max-age=31536000
Transfer-Encoding: chunked
Vary: Origin,Accept-Encoding
Error in browser dev tools
GET https://api.box.com/2.0/files/<File ID>/ 403 (Forbidden)
Error: Request failed with status code 403
at createError (createError.js?2d83:16)
at settle (settle.js?467f:18)
at XMLHttpRequest.handleLoad (xhr.js?b50d:77)

Authenticate with Docker registry API

I am trying to auth with the Docker registry API at https://registry-1.docker.io/v1/
I am trying to do calls like
https://registry-1.docker.io/v1/repositories/_/ubuntu/tags
However I keep getting a reply as below:
401
{ server: 'gunicorn/18.0',
date: 'Sun, 01 Mar 2015 12:19:13 GMT',
connection: 'close',
expires: '-1',
'content-type': 'application/json',
'www-authenticate': 'Token',
pragma: 'no-cache',
'cache-control': 'no-cache',
'content-length': '35',
'x-docker-registry-version': '0.8.2',
'x-docker-registry-config': 'prod',
'strict-transport-security': 'max-age=31536000' }
{"error": "Requires authorization"}
I have read all available guidelines as in the docs and forums.
Following those guidelines I first auth towards the HUB and request a Token. This suceeds and I get the token and a cookie from the HUB. Then I supply all this towards the Registry API as follows:
{
'set-cookie': 'csrftoken=VfHe6...; Expires=Sun, 28 Feb 2016 12:19:13 GMT; Max-Age=31449600; Path=/; Secure',
'www-authenticate': 'Token signature=VfHe6...,repository="ubuntu",access=read',
'x-docker-token': 'Token signature=VfHe6...,repository="ubuntu",access=read',
Authenticate: 'Token signature=VfHe6...,repository="ubuntu",access=read',
Authorization: 'Token signature=VfHe6...,repository="ubuntu",access=read'
}
There is this single line in the docs you shared:
Token is only returned when the X-Docker-Token header is sent with request.
You need to send 'X-Docker-Token: true' when you authenticate on the hub, then you receive in the header a 'X-Docker-Token' back. Send this out as 'Authorization:' to the registry in 'X-Docker-Endpoints' and you're in.
Good luck! :)

How to send headers while using jsonp proxy?

I am trying to get data from web services from my app to load a list and to load more on scroll using pull refresh & ListPaging plugins. I tried this with flickr API and it works fine, but problem comes when I try to access our own services because they expect "Authorization" header with Base64 encoded data and "Accept" header to decide format of response.
This is how I have defined my store:
Ext.define('myshop.store.CatalogListStore',{
extend:'Ext.data.Store',
requires: [
'myshop.model.CatalogListItem'
],
config:{
model:'myshop.model.CatalogListItem',
autoLoad :true,
proxy: {
type: 'jsonp',
url: 'http://192.168.23.89:7003/xxx-service/test/catalog/list',
useDefaultXhrHeader : false,
withCredentials:true,
method : 'GET',
headers: {
'Accept': 'application/json',
'Authorization': 'Basic YX5iOmM='
},
extraParams: {
format : 'json',
pagesize : 10
},
reader: {
type: 'json',
rootProperty: 'categories.data'
}
}
}
}
This is what I see in Chrome's network console:
Request URL:http://192.168.23.89:7003/xxx-service/test/catalog/list?_dc=1354529083930&format=json&pagesize=10&page=1&start=0&limit=25&callback=Ext.data.JsonP.callback2
Request Method:GET
Status Code:403 Forbidden
**Request Headers**
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:192.168.23.89:7003
Referer:http://localhost/myshop/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11
**Query String Parameters**
_dc:1354529083930
format:json
pagesize:10
page:1
start:0
limit:25
callback:Ext.data.JsonP.callback2
Response Headersview source
Content-Length:0
Content-Type:text/xml
Date:Mon, 03 Dec 2012 10:04:40 GMT
Server:Apache-Coyote/1.1
If I use Poster to access these services with Authorization header I am able to see response but since Headers are not passed in request I am getting "403 forbidden" status.
If I use headers like this it works :
Ext.Ajax.request({
url: 'resources/data/templates.json',
headers: {
'Accept': 'application/json',
'Authorization': 'Basic T3JkZXJSZWxlYXNlUmVmcmVzaGVyfk9yZGVyUmVsZWFzZVJlZnJlc2hlcjpPcmRlclJlbGVhc2VSZWZyZXNoZXI='
},
success: function(rsp){
}
});
but I cannot do this because I want to use listPaging plugin.
JSONP Works buy inserting the request URL as a in the the page header, if you need to authenticate your request, you will have to put it in the URL eg:
'http://192.168.23.89:7003/xxx-service/test/catalog/list?auth=1223456'
Are you certain you need to use JSONP?
See this answer for more info