I am trying to set a session variable using fetch -
const response = await fetch('http://locahost/index.php/session/set', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({token:"token"})
});
The PHP function (inside a class) that does this -
public function setSession($arr){
try{
session_start();
$_SESSION['token'] = $arr['token'];
$responseData = json_encode("SESSION token has been set to ".$_SESSION['token']);
/// sendresponsedata() -> send response back with Access-Control-Allow-Credentials: true
} catch (Error $e) {
/// Some error
}
}
The PHP function is not on the same page as the page making the fetch request. When I console.log the response on the page that sent the request, it correctly shows SESSION token has been set to token.
But if then I try to retrieve the session variable using a different request and a different function -
fetch('http://localhost/index.php/session/get',{
credentials: 'include'
})
The response I get from this is always No ongoing session
public function getSession(){
try {
session_start();
// print json_encode($_SESSION); <---- printing this shows an empty array
$responseData = json_encode((isset($_SESSION["token"])) ? $_SESSION["token"]:"No ongoing session");
/// sendresponsedata() -> send response back with Access-Control-Allow-Credentials: true
} catch (Error $e) {
/// Some error
}
}
I looked at other questions like mine but as far as I could understand, the error was because of not allowing credentials. I couldn't really understand why credentials are needed in this case reading this, but I added them anyway to check first, but that didn't change anything. As far as I could understand fetch request creates a new session everytime so this could be impossible, but this might be possible if I made an AJAX request. I am not sure I understood that correctly however.
The sendresponsedata() function works well as I have made many other fetch requests with more headers, like allowing cross-origin requests and returning required headers on preflight handshakes which all worked (and it is not really a complicated function).
What am I doing wrong and how can I achieve what I need?
Edit: Since posting I have also tried xhr requests and they don't work either.
Related
I have an axios request interceptor that adds bearer authorization via an access token. I also have a response interceptor that catches 'token expired' responses, gets a new token via a refresh mechanism, and retries the original request. This seems like it should work, except when the original request is retried, it seems to have lost all its headers. This confuses my API backend as it expects a Content-Type (which was there in the original request).
Note: I'm familiar with the large number of questions about why axios doesn't respect a custom Content-Type header. That's not my problem -- I'm not setting one -- axios does a fine job determining that on its own. I'm just confused at why the Content-Type header that axios sets itself is getting removed when resending the original request.
Relevant code:
const api = axios.create({
baseURL: "https://www.mycoolapi.com",
timeout: 5000,
withCredentials: true,
});
api.interceptors.request.use((config) => {
// Add the auth header (not messing with any other headers)
config.headers!.Authorization = `Bearer ${accessToken}`;
return config;
}, (error) => Promise.reject(error));
api.interceptors.response.use((response) => response,
async (error) => {
if (error.response.status == 401 && refreshToken && !error.config._isRetry) {
// Token expired? Refresh, then retry the original request
error.config._isRetry = true;
await refreshLogIn();
return api(error.config);
}
throw error;
});
async function refreshLogIn() {
// Use the refresh token to get a new token pair
const response = await api.post( "/token",
new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
})
);
accessToken = response.data["access_token"];
refreshToken = response.data["refresh_token"];
}
If I put a breakpoint on return api(error.config) in the response interceptor, and inspect the original request (which is in error.config), I get the following headers (reminder, I added only the Authorization header, the rest are axios defaults or calculated from the requeset):
If I then step through to the request interceptor where the original response is being retried, I get these headers instead:
Content-Type has been removed, along with what was in Symbol(defaults) (whatever that is).
What am I missing here?
As #Phil noted in the comments, this is a bug in axios >= 1.0.0. I suppose one could downgrade to 0.27.2, but I just rewrote using good old fetch. My use case was simple enough anyway, and one less dependency is never a bad thing.
I understand that there are many similar questions, but I am posting this because I feel it is slightly different.
I am trying to send a GET request to the Slack API using an HTTP request.
Specifically, the code looks like the following.
import useSWR from "swr";
const useSlackSearch = (query: string) => {
const token = process.env.NEXT_PUBLIC_SLACK_API_USER_TOKEN;
const myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + token);
const slackURL = `https://slack.com/api/search.messages?query=${query}`;
const fetcher = async (url: string) => {
const response = await fetch(url, {
headers: myHeaders,
}).then((res) => res.json());
return response;
};
const { data, error } = useSWR(slackURL, fetcher, {
revalidateOnFocus: true,
revalidateOnReconnect: true,
});
if (error) {
return console.log(`Failed to load: ${error}`);
} else if (!data) {
return console.log("Loading...");
} else {
console.log(data);
return data;
}
};
export default useSlackSearch;
The environments I'm using are as follows.
Device: MacBook Air
OS: macOS
Browser: Chrome
From: localhost:3000
To: Slack API html page (https://slack.com/api/search.messages)
After reading the MDN articles like below, I understood that
There is such a thing as a simple HTTP request as defined by MDN
If the request you want to send does not correspond to this simple request, the browser will send a preflight request
In the response to that preflight request, there is a header called Access-Control-Allow-Headers.
Only headers set to the value of this Access-Control-Allow-Headers header can be used as headers in the main request after preflighting.
In this case, I tried to use the Authorization header, but it was trapped by the above restriction.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
That's all I understand.
However, on the official Slack API page for the method in question, it says to specify the token in the Authorization header, so I'm having trouble.
I also don't understand how to specify the Access-Control-Request-Headers in the preflight header, as described in another questioner's thread. The reason is that the only thing that communicates to the Slack API is the browser in this case, and the only relevant source is JavaScript (React / Next.js to be exact)!
After that, I found preflight response from Slack API as follows;
access-control-allow-headers: slack-route, x-slack-version-ts, x-b3-traceid, x-b3-spanid, x-b3-parentspanid, x-b3-sampled, x-b3-flags
As I thought, I understand that Authorization is not allowed because it is not included as a value. So the question is how to solve it.
Furthermore, I found out later that the preflight request from the browser properly declared that it wanted to use Authorization as an actual request header. However, the preflight response did not contain the value.
Following CBroe's advice, I was able to contact the Slack help center directly, so I asked this problem. What I found out as a result is that HTTP requests from browsers are not supported as of the end of February 2022. Of course, they have received quite a lot of requests regarding this, so they hope to address it at some point.
This time, the browser sent Access-Control-Request-Headers:Authorization in the preflight request. But the Slack API server side did not allow the Authorization header in the request from the browser. Therefore, Authorization was not set in the Access-Control-Allow-Headers in the preflight response from the Slack API side.
As a result, the response from the Slack API side returned Invalid Auth, even though Authorization was added as a header when making an actual request from the browser.
Through this error, I gained a deeper understanding of HTTP requests such as CORS and preflighting, but since it is not explicitly written on the official Slack website, I left it here.
What is Preflight: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
What is Access-Control-Allow-Header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
What is CORS simple request: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
I could not get the Authorization header to work either. However, Slack provided this example for adding token authentication to the Post body following the deprecation of the query parameters method.
This worked for me to make Web API calls to Slack from the browser (for testing) so that Slack would read the token for authentication. Note, according to Slack's best practices for security, user and bot tokens should be stored with care and not used in client-side Javascript:
try {
const res = await fetch("https://slack.com/api/conversations.list", {
method: "POST",
body: `token=${TOKEN}`, // body data type must match "Content-Type" header
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}).catch((error) => {
console.log(error);
});
if (!res.ok) {
throw new Error(`Server error ${res.status}`);
} else {
const data = await res.json();
console.log(data);
}
} catch (error) {
console.log(error);
}
using token in request body instead of Authorization header worked for me.
axios({
method: 'post',
url: 'https://slack.com/api/chat.postMessage',
data: `text=Hi&channel=D048GGYTJUK&token=${process.env.TOKEN}`
})
What is the reason the server is returning object as 'undefined' and 'XMLHttpRequest cannot load the "URL" Response for preflight is invalid (redirect).
Flow of app - its just a normal post service sending document details to the server in return should return an object holding various parameters, but its returning 'undefined'
The service for posting the document
fileUpload: {
method: 'POST',
url: config.apiPath + 'employee/service/pushRecords', //this is the URL that should return an object with different set of parameters (currently its returning Error error [undefined])
isArray: false,
params: {},
headers: {
'content-type': undefined
}
},
above service i have used after creating formdata w.r.t document
function registerFormdata(files, fieldName) {
files = files || [];
fieldName = fieldName || 'FileSent';
var returnData = new FormData();
_.each(files, function (file, ind) {
returnData.append(fieldName,file);
});
return returnData;
}
now this is the controller where these services are used
function sendFilesToServer() {
var formData = employeePushService.registerFormdata(directive.dropZoneFile.fileToUpload);
return docUploadService.fileUpload(formData)
.then(function(document) {
// Extra actions but here the server should be returning an object with set of parameters but in browser console its Error [undefined]
}).catch(logger.error);
}
Assuming that the URL target in yout post is correct, it seems that you have a CORS problem, let me explain some things.
I don't know if the server side API it's developed by yourself, if it is, you need to add the CORS access, your server must return this header:
Access-Control-Allow-Origin: http://foo.example
You can replace http://foo.example by *, it means that all request origin will have access.
First, you need to know that when in the client you make an AJAX CORS request, your browser first do a request to the server to check if the server allow the request, this request is a OPTION method, you can see this if, for example in chrome, you enable the dev tools, there, in the network tab you can see that request.
So, in that OPTIONS request, the server must set in the response headers, the Access-Control-Allow-Origin header.
So, you must check this steps, your problem is that the server side is not allowing your request.
By the way, not all the content-type are supported in CORS request, here you have more information that sure will be helpfull.
Another link to be helpfull for the problem when a 302 happens due to a redirect. In that case, the POST response must also include the Access-Control-Allow-Origin header.
I am building a small Angular frontend support by a REST api in the backend, but I have ran into a very strange problem: doing http.post(url, data, params) results in nothing happening (there's no sign the request ever hits the webserver, in Chrome Developer tools there's absolutely no request logged as opposed to this.http.get() requests, which work fine for URLs on the same server).
export class RestComponent {
constructor ( private http: Http ) {}
sendStuff() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post('http://localhost:3021/api/data', {'data': 3}, options)
.catch(this.handleError);
}
}
CORS is enabled on the server
this.http.get on the URL works as expected
there's no evidence in the server logs that the request was ever sent
there's no evidence in Chrome developer tools that the request was sent (no such post request)
logging stuff in the method just before the .post() call shows that everything is as expected (headers, data, etc)
replicating the request in Postman works (identical headers and data)
tried stringyfying the data as well
the error handler does some simple logging, but it's not triggered
I feel quite dumb as it must be something that's fairly obvious yet it escapes me. I've created a simple component which just two methods, one that sends hardcoded data via post and the other that fetches a hardcoded json via get, the second works but the first doesn't.
Would appreciate any pointers.
Thanks!
Essentially you had created just an observable and Observable are lazy in nature. They will get call/emit only when someone has subscribe to them. Hence you have to call subscribe to Observable returned from it to make your code working. Apart from this Everything seems to be perfect.
sendStuff() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:3021/api/data', {'data': 3}, options)
.catch(this.handleError)
.subscribe(
(data) => console.log(data)
);
}
There's no server code for us to see but make sure that the route is setup to expect content-type application/json because by default a post route will expect post data, depending on what technology you are using for your server.
Also try just doing a relative path maybe: .post('/api/data')
This is the story of a bird who wants to work for the post but fails during his preflight test...
App built with Laravel being used as a RESTful API and AngularJS/ionic.
My API calls were working fine until...for an unknown reason it stopped.
Although I set the withCredentials for the angularJS side of the call, the preflight OPTIONS are not sending a cookie but I am receiving one back from Laravel. How can we disable OPTIONS to return a cookie laravel_session?
It messes up the CORS as it sets a new session which will obviously be different on every POST.
For Laravel side I use the package Laravel/CORS from #barryvdh with the following configuration:
'*' => array(
'supportsCredentials' => true,
'allowedOrigins' => array('*'),
'allowedHeaders' => array('*'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'PATCH', 'OPTIONS', 'DELETE'),
'maxAge' => 36000,
'hosts' => array('api.*'),
)
On the Angular side I have the following:
$http({
method: 'POST',
url: 'http://api.blabla.local/banana',
data: data,
withCredentials: true
})
My GET calls work fine and I have one running at start of the app to fetch the CSRF from laravel that I send back when needed.
Right now the following happens:
1. Preflight OPTIONS > request has no cookies for the session. Reponse = 200 with a different session cookie which will cause the CSRF to cause all the time. [thoughts: the withCredentials does not work with the OPTIONS call]
2. POST > fails with 500, in the headers I see no response but it did send the cookie/session [thoughts: credentials are passed to it but they are also the wrong ones since they have changed on server side because of the preflight option]. Error message says it is not authorized origin.
What's going on? I've been trying for hours now and checked a lot of other posts but nothing seems to help! Can I get rid of the preflight, how? Or is the problem somewhere else (server side I'm using Laravel Homestead)?
I feel that the real issue is that the OPTIONS returns a session cookie or simply that the request does include one!
Thanks for your help, I've been stuck for hours and I'm going crazzy on that...
In the filters.php under L4.2 I ended up using this:
The problem is old so not sure it's the only thing I did but looks like it:
App::before(function($request)
{
//
// Enable CORS
// In production, replace * with http://yourdomain.com
header("Access-Control-Allow-Origin: http://mydomain.local");
header('Access-Control-Allow-Credentials: true'); //optional
if (Request::getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
$headers = [
'Access-Control-Allow-Methods'=> 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type'
];
return Response::make('You are connected to the API', 200, $headers);
}
});
App::after(function($request, $response)
{
//
});
JWT could be good for ionic and angular..
Check http://packalyst.com/packages/package/tymon/jwt-auth
also https://www.youtube.com/watch?v=vIGZxeQUUFU