Accessing Set-Cookie value from response.headers in axios - vue.js

I am using VueJS and Axios to send a request like this:
axiosAPI.get('/login/flows', {params: {id: 'string'}})
.then(res => {
console.log('cookie', res.headers)
}
In return server sends me this response:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Type
Cache-Control: private, no-cache, no-store, must-revalidate
Content-Length: 646
Content-Type: application/json; charset=utf-8
Date: Thu,xxxx 13:56:21 GMT
Set-Cookie: csrf_token=Lxv3zynm1Fua0hU0/W1+R2w=; Path=/.ory/kratos/public/; Domain=x.y ; Max-Age=31536000; HttpOnly; SameSite=Lax
Vary: Origin
Vary: Cookie
As you can see, server sends a csrf-token in Set-Cookies. but when I try to print out the headers I can not get and store the csrf-token. In addition, browser doesn't store the token at all in the storage section.
I need to use the csrf-token inside of this cookie but I don't know how I can do this?
Note: i don't have any access to back-end codes.

Maybe you can use the axios-cookiejar-support.
https://www.npmjs.com/package/axios-cookiejar-support
A medium article showing how to use it.
https://medium.com/#adityasrivast/handling-cookies-with-axios-872790241a9b
Sample (getting cookie from a login page):
const axios = require('axios');
const wrapper = require('axios-cookiejar-support').wrapper;
const CookieJar = require('tough-cookie').CookieJar;
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
const url = '<your url>';
const params = new URLSearchParams();
params.append('username', '<username>');
params.append('password', '<password>');
client.post(`${url}/Login`, params, {
headers: {
'Accept': '*/*'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Using this will get you the whole string for that header:
const cookieHeaders = res.headers['Set-Cookie'];
After that, you could split the string in an array with
cookieHeaders.split('; ');
In the array, you can then get the specific one you need.

Related

Donwload file with POST method in React Native and Expo

How can I download a file using the POST method along with some headers and data (of the type: "content-type: application/x-www-form-urlencoded") in React Native?
When I send a request to the URL, the following is returned in the Response Header:
content-disposition: attachment; filename="PAPR_Pginas_Web_2.pdf"
content-type: application/pdf
date: Sun, 07 Aug 2022 13:59:00 GMT
last-modified: Thu, 01 Jan 1970 00:00:00 GMT
server: Apache
strict-transport-security: max-age=86400
x-powered-by: JSF/1.2
x-xss-protection: 1; mode=block
I'm using this code:
const donwloadPDF = async (uri) => {
const downloadInstance = FileSystem.createDownloadResumable(uri, FileSystem.documentDirectory + "file.pdf");
const result = await downloadInstance.downloadAsync();
if (result.status === 200) {
Sharing.shareAsync(result.uri, { dialogTitle: "Share or Save" });
} else {
console.log("Failed to Download");
}
};
const getFile = async (payload) => {
try {
const response = await fetch(URL, {
method: "POST",
headers: headers2,
body: formBody(payload),
});
const content = await response.json();
donwloadPDF(content); // Some URI
} catch (error) {
console.error(error);
}
};
But is returned the error: JSON Parse error: Unrecognized token '%'

Authorization token Axios sending but Express.js not receiving

I have a Vue app consuming Express API via Axios, trying to access an authenticated route. Including the Auth token in Postman Request header, the route yields the correct json response. However, from the Vue front end, it returns the error 404 unauthorized, no token found.
here are the request headers:
Request URL: http://localhost:8000/api/groups
Request Method: GET
Status Code: 401 Unauthorized
Remote Address: [::1]:8000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 2587
Content-Security-Policy: default-src 'none'
Content-Type: text/html; charset=utf-8
Date: Sat, 14 Sep 2019 21:47:42 GMT
X-Content-Type-Options: nosniff
X-Powered-By: Express
Provisional headers are shown
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
Referer: http://localhost:8080/groups
Sec-Fetch-Mode: cors
token: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJ0d29AZ21haWwuY29tIiwiaWQiOjIsImV4cCI6MTU3MzY4NTI0NiwiaWF0IjoxNTY4NDk3NjQ2fQ.6zDOfTQzf4KW5ry4mJFaLXnUL7wAnHP_8W0B0JEW5DA
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Here is the response:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>UnauthorizedError: No authorization token was found<br> at middleware (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express-jwt/lib/index.js:76:21)<br> at Layer.handle [as handle_request] (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/layer.js:95:5)<br> at next (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/route.js:137:13)<br> at Route.dispatch (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/route.js:112:3)<br> at Layer.handle [as handle_request] (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/layer.js:95:5)<br> at /Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:281:22<br> at Function.process_params (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:335:12)<br> at next (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:275:10)<br> at Function.handle (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:174:3)<br> at router (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:47:12)<br> at Layer.handle [as handle_request] (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/layer.js:95:5)<br> at trim_prefix (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:317:13)<br> at /Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:284:7<br> at Function.process_params (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:335:12)<br> at next (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/express/lib/router/index.js:275:10)<br> at jsonParser (/Users/dariusgoore/development/writerboard/writerboard-express-api/node_modules/body-parser/lib/types/json.js:110:7)</pre>
</body>
</html>
Here is the Base config for Axios (the console.log statement retrieves the correct result):
import axios from 'axios'
const token = localStorage.getItem('token')
console.log('this is the token from localStorage ls', token)
export default () => {
return axios.create({
baseURL: process.env.VUE_APP_ROOT_API,
headers: {
'Content-Type': 'application/json',
token: token,
},
validateStatus: function () {
return true;
}
})
}
Here is my cors config in Express server:
const cors = require('cors');
const app = express()
...
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
Here is the authentication middleware that should retrieve the token (but per the console log is getting 'undefined'):
const jwt = require('express-jwt');
const getTokenFromHeaders = (req) => {
const { headers: { authorization } } = req;
console.log('this is the authorization token from the header: ', authorization);
if(authorization && authorization.split(' ')[0] === 'Token') {
return authorization.split(' ')[1];
}
return null;
};
const auth = {
required: jwt({
secret: 'secret',
userProperty: 'user',
getToken: getTokenFromHeaders,
}),
optional: jwt({
secret: 'secret',
userProperty: 'user',
getToken: getTokenFromHeaders,
credentialsRequired: false,
}),
};
module.exports = auth;
here is the express route I am trying to secure:
const express = require('express');
const auth = require('../middlewares/authenticate');
const User = require('../models/User');
const knex = User.knex();
let router = express.Router();
router.get('/', auth.required, async (req, res) => {
console.log('this is the req.user from /groups', req.user);
const userId = req.user.id
let results = await knex.raw(`SELECT users.id, users.username, groups.id, groups.name FROM users JOIN memberships ON users.id = memberships.users_id JOIN groups ON memberships.groups_id = groups.id WHERE users.id = ${userId}`);
console.log(results);
res.json(results.rows);
});
Your server has this:
const { headers: { authorization } } = req;
That appears to be looking for a header called authorization.
Your request has this:
token: Token eyJhbGciOiJIUzI1...
due to this:
headers: {
'Content-Type': 'application/json',
token: token,
},
That header is called token, not authorization.

pass sessions saved in cookies with post() automatically angular

I have seen a few bug reports on github but couldn't figure out my issue. I have cookies that the server sets. Now during POST method,I want to pass this data back to the server. It is an Observable because response from the server will determine further steps to take. Note that I have no access to the backend but CORS and credentials are set. My current code is:
public logout () : Observable<any> {
/*
Send a clear session request to cbase
*/
let vm : any = this;
const httpPostOptions =
{
headers:
new HttpHeaders (
{
"Content-Type": "application/x-www-form-urlencoded"
}),
withCredentials: true
};
return new Observable((observer) => {
vm.http.post(
Config.syncGatewayLoginStage + 'logout/', httpPostOptions
).subscribe(
data => {
observer.next(data);
},
err => { observer.error(err); console.log(err); },
() => {
observer.complete();
}
);
});
}
The server responds with error 500 that the session doesn't exist and of course, I see no session cookies passed to the server in the request header even though I see cookies set.
The server response is:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
Connection: keep-alive
Content-Length: 1406
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Wed, 20 Feb 2019 10:09:29 GMT
Vary: Origin
X-Content-Type-Options: nosniff
X-Powered-By: Express

How to use fetch() in react native with headers json?

Postman output:
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type: application/json
Date: Fri, 08 Feb 2019 12:13:36 GMT
{"status":1,"msg":"success","celeb":[{"id":1,"name":"Test Name"....
I'm getting my json in postman like this.
when I try to use fetch(), I'm getting an error json parse error, unknown identifier HTTP
fetch('https://myurl/fetch')
.then((response) => response.json())
.then((response) => {...}
let func = async () => {
const url = 'https://myurl/fetch';
const data = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: await AsyncStorage.getItem(ACCESS_TOKEN), /*or whatever you have on your api*/
}),
};
const response = await fetch(url , data);
const responseData = await response.json();
console.log(responseData);
}
I believe you are missing to set to configure you API call method, headers, mode etc... Check out Fetch Examples for a better explanation.

Trouble getting an Authentication Token using Axios for React

I'm trying to grab an authentication token using axios in a react app.
Here is the error I'm getting is:
"XMLHttpRequest cannot load https://api.mmitnetwork.com/Token. Response for preflight has invalid HTTP status code 400"
Here is my code.
var App = React.createClass({
getInitialState() {
return {
token: ''
}
},
componentDidMount() {
var _this = this;
axios.post('https://api.mmitnetwork.com/Token', {
grant_type: 'password',
username: 'jpdesigning',
password: 'Upahem2_88'
}).then((response) => {
console.log('Success!')
_this.setState({
token: response.data
})
}).catch((error) => {
console.log(error)
})
},
render() {
return (
<div className="App">
{this.state.token}
</div>
);
}
})
export default App;
Your server needs to allow cross-origin (CORS) clients to access your headers by setting the following header on your server's response and telling it which headers they are (here you are allowing two headers: Authorization & Permissions - i.e. including custom headers)
Access-Control-Expose-Headers: Authorization, Permissions
Headers that are accessible by default:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
Read here Access-Control-Expose-Headers
example from php server for full CORS access
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Expose-Headers: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size,
X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
you need to set withCredentials: true, header , this will send the cookie along with this request