Get XDEBUG_SESSION_START header in Phalcon request - php

I am trying to remotely start debugger in multiple microservices using Phalcon, the first microservice accepts XDEBUG_SESSION_START header but I cannot get the header in the request when I instantiate the Request object so I guess that Apache is removing it after the debugger starts.
Is it exists any option or way to disable this behavior and make the Phalcon code know when the Xdebug flag is present in the Request in order to forward that flag when calling other microservices?
I know that I can set auto_start option for Xdebug but that option seems to slow down the microservices.
The final code should looks similar to:
$DEBUG = $request.getHeaders()['XDEBUG_SESSION_START']
if (!is_empty($DEBUG)) {
$headers['XDEBUG_SESSION_START'] == 1;
}
....
I think this would be OK and it will not cause problems even when code will be deployed to PROD environments.

Related

access to xmlhttprequest has been blocked by cors policy no 'access-control-allow-origin' [duplicate]

I am working on an app using Vue js.
According to my setting I need to pass to a variable to my URL when setting change.
<!-- language: lang-js -->
$.get('http://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) {
// some code...
});
But when my app hit on URL, it shows the following message.
Failed to load http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26: Redirect from 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26' to 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
In addition to what awd mentioned about getting the person responsible for the server to reconfigure (an impractical solution for local development) I use a change-origin chrome plugin like this:
Moesif Orign & CORS Changer (use to be free but now wants a work email address >_>)
Allow CORS: Access-Control-Allow-Origin
You can make your local dev server (ex: localhost:8080) to appear to be coming from 172.16.1.157:8002 or any other domain.
In case the 2nd plugin link breaks in the future or the plugin writer decides to capitalize off the fame of this thread, open your browser's
plugin marketplace and search "allow cors", there's going to be a
bunch of them.
Thanks all, I solved by this extension on chrome.
Allow CORS: Access-Control-Allow-Origin
If you have control over your server, you can use PHP:
<?PHP
header('Access-Control-Allow-Origin: *');
?>
Ask the person maintaining the server at http://172.16.1.157:8002/ to add your hostname to Access-Control-Allow-Origin hosts, the server should return a header similar to the following with the response-
Access-Control-Allow-Origin: yourhostname:port
Using npm:
To allow cross-origin requests install 'cors':
npm i cors
Add this in the server-side:
let cors = require("cors");
app.use(cors());
When you have this problem with Chrome, you don't need an Extension.
Start Chrome from the Console:
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Maybe you have to close all Tabs in Chrome and restart it.
I will assume that you're a front-end developer only and that you don't have access to the backend of the application (regarding the tags of the question).
Short answer on how to properly solve this in your case? You can't, you'll need somebody else.
What is this about?
You need to understand that CORS is a security thing, it's not just here to annoy you just for fun.
It's purpose is to mainly prevent the usage of a (malicious) HTTP call from a non-whitelisted frontend to your backend with some critical mutation.
You could give a look to this YouTube video or any other one really, but I recommend a visual video because text-based explanation can be quite hard to understand.
You also need to understand that if you use Postman or any other tool to try your API call, you will not get the CORS issue. The reason being that those tools are not Web frontends but rather some server-based tools.
Hence, don't be surprised if something is working there but not in your Vue app, the context is different.
Now, how to solve this?
Depending of the framework used by your backend team, the syntax may be quite different but overall, you'll need to tell them to provide something like Access-Control-Allow-Origin: http://localhost:3000 (or any other port you'll be using).
PS: Using Access-Control-Allow-Origin: * would be quite risky because it would allow anybody to access it, hence why a stricter rule is recommended.
If you're using a service, like an API to send SMS, payment, some Google console or something else really, you'll need to allow your localhost in the dashboard of the service. Ask for credentials to your manager or Tech Lead.
If you have access to the backend, you could it yourself as shown here (ExpressJS in this example): https://flaviocopes.com/cors/
How to hack it in a dirty way?
If you're in a damn hurry and want to get something really dirty, you could use a lot of various hacks a listed in the other answers, here's a quick list:
use any extension who is able to create a middleware and forward the request to the backend (it will work because it's not directly coming from your frontend)
force your browser to disable CORS, not sure how this would actually solve the issue
use a proxy, if you're using Nuxt2, #nuxtjs/proxy is a popular one but any kind of proxy (even a real backend will do the job)
any other hack related somehow to the 3 listed above...
At the end, solving the CORS issue can be done quite fast and easily. You only need to communicate with your team or find something on your side (if you have access to the backend/admin dashboard of some service).
I heavily do recommend trying get it right from the beginning because it's related to security and that it may be forgotten down the road...
The approved answer to this question is not valid.
You need to set headers on your server-side code
app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Methods','Content-Type','Authorization');
next();
})
You can also try a chrome extension to add these headers automatically.
Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:
Header set Access-Control-Allow-Origin "*"
And then restart apache.
Altering headers requires the use of mod_headers. Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled.
I had the same problem in my Vue.js and SpringBoot projects. If somebody work with spring you can add this code:
#Bean
public FilterRegistrationBean simpleCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// *** URL below needs to match the Vue client URL and port ***
config.setAllowedOrigins(Collections.singletonList("http://localhost:8080"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedHeaders(Collections.singletonList("*"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
I found solution in this article Build a Simple CRUD App with Spring Boot and Vue.js
You are making a request to external domain 172.16.1.157:8002/ from your local development server that is why it is giving cross origin exception.
Either you have to allow headers Access-Control-Allow-Origin:* in both frontend and backend or alternatively use this extension cors header toggle - chrome extension unless you host backend and frontend on the same domain.
Try running this command in your terminal and then test it again.
curl -H "origin: originHost" -v "RequestedResource"
Eg:
If my originHost equals https://localhost:8081/ and my RequestedResource equals https://example.com/
My command would be as below:
curl -H "origin: https://localhost:8081/" -v "https://example.com/"
If you can notice the following line then it should work for you.
< access-control-allow-origin: *
Hope this helps.
Do specify #CrossOrigin(origins = "http://localhost:8081")
in Controller class.
You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!
You won't believe this,
Make sure to add "." at the end of the "url"
I got a similar error with this code:
fetch(https://itunes.apple.com/search?term=jack+johnson)
.then( response => {
return response.json();
})
.then(data => {
console.log(data.results);
}).catch(error => console.log('Request failed:', error))
The error I got:
Access to fetch at 'https://itunes.apple.com/search?term=jack+johnson'
from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But I realized after a lot of research that the problem was that I did not copy the
right URL address from the iTunes API documentation.
It should have been
https://itunes.apple.com/search?term=jack+johnson.
not
https://itunes.apple.com/search?term=jack+johnson
Notice the dot at the end
There is a huge explanation about why the dot is important quoting issues about DNS and character encoding but the truth is you probably do not care. Try adding the dot it might work for you too.
When I added the "." everything worked like a charm.
I hope it works for you too.
install:
npm i cors
Then include cors():
app.get("/list",cors(),(req,res) =>{
});
In addition to the Berke Kaan Cetinkaya's answer.
If you have control over your server, you can do the following in ExpressJs:
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
https://enable-cors.org/server_expressjs.html
I tried this code,and that works for me.You can see the documentation in this link
var io = require("socket.io")(http, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
})
The reason that I came across this error was that I hadn't updated the path for different environments.
you have to customize security for your browser or allow permission through customizing security. (it is impractical for your local testing)
to know more about please go through the link.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
These errors may be caused due to follow reasons, ensure the following steps are followed. To connect the local host with the local virtual machine(host). Here, I'am connecting http://localhost:3001/ to the http://abc.test Steps to be followed:
1.We have to allow CORS, placing Access-Control-Allow-Origin: in header of request
may not work. Install a google extension which enables a CORS request.*
2.Make sure the credentials you provide in the request are valid.
3.Make sure the vagrant has been provisioned. Try vagrant up --provision this make the localhost connect to db of the homestead.
Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' }
this point is very important.
Another solution to this problem in a specific scenario :
If
AWS APIGW is your backend with authentication enabled and
authentication fails,
your browser may end up complaining about CORS even if CORS is enabled in APIGW. You also need to enable CORS for 4XX as follows
API:YourAPI > Resources > /YourResource > Actions > Enable CORS > Gateway Responses for yourAPI check Default 4XX
Authentication will still fail but it won't look like CORS is the root cause
$.get('https://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) {
// some code...
});
Just put "https" .

Really force http to https in Laravel

I have this Laravel App which I'm deplying to Heroku.
I have followed all of the steps until I encountered a problem relating some assets (asset('css/app.css'), for example) refering to http urls, instead of https urls.
I solved that by adding
if(config('app.env')==='production'){
\URL::forceScheme('https');
}
in the boot method of my AppServiceProvider.php file, and it worked.
But now I have encountered another http related problem that the previous code couldn't solve.
I am fetching my data using simplePaginate() function like so
public function index(Question $question){
$answers = $question->answers()->with('user');
return $answers->simplePaginate(3);
}
This code returns me a response with my 3 answers, as well as with a property called 'next_page_url'
which is, still, plain http (not https as i need it to be).
What can I do for this to be https as Heroku requires?
Heroku's load balancing setup means the indication of whether the request is HTTP or HTTPS comes from the X-Forwarded-Proto header. (Laravel also needs the X-Forwarded-For header to get the users' real IP addresses, incidentally.)
By default, Laravel doesn't trust these headers (as in a different setup it might come from a malicious client), so none of the requests will be detected as HTTPS. You can fix this by configuring the Laravel trusted proxy to trust the header.
In the default config, just setting $proxies = '*', will do the trick, and is safe on Heroku because the load balancers can't be bypassed by end users.
The correct way is to change the URL of your app to https://example.com in the configuration file (.env file as an example). Just write APP_URL=https://example.com
But, when you use Heroku - their balancers can route your requests to https://yourDomain.com to your application over HTTP. So, the Laravel app receives the request to http://yourDomain.com and decides that you need a response with HTTP links.
As #seejayoz said you need to configure trusted proxies list for your app.
I think you can use withPath (or setPath alias) :
$pagi=$answers->simplePaginate(3);
$pagi->withPath("https://link/xxx/");
return $pagi;

Setting PHP environment variable on GAE dev mode (dev_appserver.py)

I have Zend Framework project running on Google App Engine. Everything works great, with the exception of one thing:
I can't set an environment variable to tell Zend that I'm in development mode
Any ideas?
(I'm using PHP 5.4 in Ubuntu)
What I've tried
(Obviously I don't want to set the variable through app.yaml... I can't set it through .htaccess because it's not used. I would rather not have to add any conditions in my code to possibly set the variable that way, either)
I'm using PHPStorm (IDE), which has a nice plugin for GAE. It even has an option in the project configurations for environment variables - except that it doesn't work. I'm setting the variable in PHPStorm (Edit Configurations > Google App Engine for PHP > Command Line > Environment Variables), but if I do a
getenv()
from code, it returns
boolean false
Why
My goal in all this is to dynamically load the development configurations for my project, particuarly so I can use MySQL locally, instead of connecting up to CloudSQL while developing and testing the apps.
The solution I'm going with, based on the comments by #tim-hoffman is the following little bit of logic on my /public/index.php file, placed before the APPLICATION_ENV constant is defined:
$env = getenv("SERVER_SOFTWARE");
if ($env !== false) {
if ((bool)preg_match("/development/", strtolower($env))) {
define("APPLICATION_ENV", "development");
}
}
In development mode, SERVER_SOFTWARE will return the string "Development/X.X" (version number), and in production, it'll be "Google App Engine/X.Y.Z"

OpenID login code fails in live server

I want to implement an OpenID login system with latest LightOpenID release. I'm testing the example provided with the source code line by line (I just replaced localhost with $_SERVER['HTTP_HOST'] in the constructor).
The issue is that everything works fine in my development box inside a private network (PHP/5.3.6 on Windows Vista) but validation always fails in my life server at the HSP public network (PHP/5.3.3 on CentOS).
I've added var_dump()'s all around and I can tell you that both copies of the code produce exactly the same request parameters and receive exactly the same response parameters (via GET). Only openid.assoc_handle, openid.sig, openid.response_nonce and openid.return_to have different values, which I guess is the expected behaviour.
However, my dev box receives this from the OpenID provider (no matter which one I use):
is_valid:true
ns:http://specs.openid.net/auth/2.0
... and my live fox receives this:
is_valid:false
ns:http://specs.openid.net/auth/2.0
There aren't any non-ASCII characters involved so it can't be an encoding issue. There must be something wrong in my hosting service but I just can't figure out what.
I need suggestions about possible causes and troubleshooting tips.
I've isolated the problem and found a workaround. The request() method makes some auto-detection to find out how to stablish HTTP connections:
protected function request($url, $method='GET', $params=array(), $update_claimed_id=false)
{
if (function_exists('curl_init')
&& (!in_array('https', stream_get_wrappers()) || !ini_get('safe_mode') && !ini_get('open_basedir'))
) {
return $this->request_curl($url, $method, $params, $update_claimed_id);
}
return $this->request_streams($url, $method, $params, $update_claimed_id);
}
In my dev box is uses CURL but in my live box it uses file_get_contents() because the check fails. The reason is that the open_basedir directive is not empty.
If I force LightOpenID to use CURL, everything runs smoothly.
Update #1: LightOpenID was right when deciding that curl was not usable. I found this in the log file:
CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled
or an open_basedir is set
As for the file_get_contents() version, I suspect I've found a typo in the library:
Index: lightopenid/openid.php
===================================================================
--- lightopenid/openid.php (0.60)
+++ lightopenid/openid.php (working copy)
## -349,7 +349,7 ##
$this->headers = $this->parse_header_array($http_response_header, $update_claimed_id);
}
- return file_get_contents($url, false, $context);
+ return $data;
}
protected function request($url, $method='GET', $params=array(), $update_claimed_id=false)
I've notified the author and he's confirmed it's a bug. I'll report back if it gets fixed.
Update #2: The bug was fixed in master branch on June 2012. It's still not part of the stable release but can be downloaded from the code repository.
Just a shot in the dark but when I worked with OpenID (not lightopenid) but a library for CodeIgniter, I got a similar issue when my permissions were not set correctly for the nonce cache folder. Maybe its a simple permission issue for storage?

Twitter OAuth failing to work (PHP)

I have the TwitterOAuth class and demonstration running on a local development server and I cannot get it to authorize. I have entered the new CONSUMER_KEY and CONSUMER_SECRET in the config.php. I have also synced the server time to NTP. I get the error message: 'Could not connect to Twitter. Refresh the page or try again later.'
var_dump($connection->http_code);
results:
int 0
ANY help or advise would be appreciated.
I am running PHP 5.3
When I try to ping the api server I can't.
C:\Users\Owner>ping api.twitter.com
Ping request could not find host api.twitter.com. Please check the name and try
again.
could this be the problem ?
I had some issues with this process as well. I don't exactly recall what resolved this error, but I followed This Tutorial (albeit a bit out of date) and made sure I explicitly set the callback URL in the twitter panel for my app. Also, and I believe this one also caused the int 0 return for me, make sure that if you are going with a hosting provider they allow CURL requests.
step 1: https://apps.twitter.com/app or go to your app setting
step 2: Unchecked the (Enable Callback Locking (It is recommended to enable callback locking to ensure apps cannot overwrite the callback url)) This box..
save and exit and check..
ThankYou..!

Categories