I have a php file on an second server that creates JWT Tokens using the Firebase Token Generator (https://github.com/firebase/php-jwt).
When I make a post using .ajax in my app, it keeps giving me a 500 error. I think that use \Firebase\JWT\JWT; in the php file may be causing this issue, but i am not sure why. Would appreciate any assistance with pointing me in the right direction.
Here is the PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?PHP
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
// include('./config.php');
require_once '../vendor/firebase/php-jwt/src/BeforeValidException.php';
require_once '../vendor/firebase/php-jwt/src/ExpiredException.php';
require_once '../vendor/firebase/php-jwt/src/SignatureInvalidException.php';
require_once '../vendor/firebase/php-jwt/src/JWT.php';
$issuedAt = time();
$expire = $issuedAt + 86400; //add 24 hours
$personalID = $_POST['personalID'];
$email = $_POST['email'];
$key = "stringkeyexample";
$token = array(
"iss" => "example.com",
"aud" => "example.org",
"iat" => $issuedAt,
"nbf" => $issuedAt,
"exp" => $expire,
"pid" => $personalID
);
if ($puid){
use \Firebase\JWT\JWT;
$jwt = JWT::encode($token, $key);
print_r($jwt);
}
here is the .ajax:
$.ajax({
type: "POST"
, dataType: "html"
, url: "https://external-server.com/jwt.php"
, data: {personalID: personalID, email: email}
, beforeSend: function(){
console.log("before");
}
, complete: function(){
console.log("done");
}
, success: function(html){
console.log(html);
}
});
Related
Given the following code:
fetch(mockproxy+myphp.php,{
method: 'POST',
headers:{'Token':token["token"]},
body: name,
}).then((response) => response.json())
.then((json)=>{
toast.success(JSON.stringify(json));
})
.catch((err) => {
toast.error(JSON.stringify(err));
})
}
mockproxy is helping bypass CORSS. The file looks like this:
const corsAnywhere = require('cors-anywhere');
const express = require('express');
const apicache = require('apicache');
const expressHttpProxy = require('express-http-proxy');
const CORS_PROXY_PORT = 5000;
// Create CORS Anywhere server
corsAnywhere.createServer({}).listen(CORS_PROXY_PORT, () => {
console.log(
`Internal CORS Anywhere server started at port ${CORS_PROXY_PORT}`
);
});
// Create express Cache server
let app = express();
// Register cache middleware for GET and OPTIONS verbs
app.get('/*', cacheMiddleware());
app.options('/*', cacheMiddleware());
// Proxy to CORS server when request misses cache
app.use(expressHttpProxy(`localhost:${CORS_PROXY_PORT}`));
const APP_PORT = process.env.PORT || 5080;
app.listen(APP_PORT, () => {
console.log(`External CORS cache server started at port ${APP_PORT}`);
});
/**
* Construct the caching middleware
*/
function cacheMiddleware() {
const cacheOptions = {
statusCodes: { include: [200] },
defaultDuration: 60000,
appendKey: (req, res) => req.method
};
let cacheMiddleware = apicache.options(cacheOptions).middleware();
return cacheMiddleware;
}
And the server is a shared server where I upload the PHP files so they can access to the DB. The php receives the data and give a response when I use postman but not when I execute the fetch from the dev website, I'm using react, I think it doesn't matter in this case.
The PHP file:
<?php
$headers = apache_request_headers();
header("Access-Control-Allow-Origin: *, ");
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
exit;
}
if (isset($_POST["name"])) {
echo json_encode(" name" . $_POST["name"]); //returned on postman
}else{
echo json_encode("no name"); //returned on development.
}
exit;
So this is a code i use when i want to fetch all data from a form. You can obviously not loop through all forms like i do below but just your single form.
// Query all forms in the DOM or a specific one if you want
const forms = document.querySelectorAll('form');
// Loop through them
forms.forEach((form) => {
// if method is post
if (form.method === 'post') {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// prepare the data
let data = new FormData(form);
// fetch using the form's
fetch(form.action, {
method: 'post',
body: data,
})
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
// if not post (get really)
} else {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// build the URL query params from the submitted data
const data = new URLSearchParams(new FormData(form).entries());
// Fetch, URL is formed from the action, append ? and then the query params
fetch(form.action + '?' + data)
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
}
});
I'm currently working on a PHP REST API for a uni project, which uses JSON web tokens passed from mobile web applications using PhoneGap, or my desktop during development.
When sending the token to my server page "friends/read.php" using ajax, the server was picking up the Authorization header correctly with
$headers = getallheaders();
$authHeader = $headers['Authorization'];
but stopped doing so after several successful runs. After that point, the header is no longer being picked up.
My request code is as follows:
$.ajax({
url: "http://localhost/chordstruck/api/friends/read.php",
type: "GET",
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('jwt'));
},
datatype: "json",
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
Oddly enough, when killing the PHP script prematurely with die("test") and then removing die() again, the server will then start picking up the Authorization header for several more requests.
Read.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
$config = require_once '../config/core.php';
require_once '../config/jwt_helper.php';
// get database connection
include_once '../config/database.php';
// instantiate profile object
include_once '../objects/profile.php';
$headers = getallheaders();
$authHeader = $headers['Authorization'];
$token;
if ($authHeader) {
list($jwt) = sscanf((string)$authHeader, 'Bearer %s');
if ($jwt) {
try {
$key = $config['jwt_key'];
$token = JWT::decode($jwt, $key, array('HS512'));
} catch (Exception $e) {
header('HTTP/1.0 401 Unauthorized');
exit();
}
} else {
header('HTTP/1.0 400 Bad Request');
exit();
}
} else {
header('HTTP/1.0 400 No Header Found');
exit();
}
echo "success";
?>
I have been encountering a CORS issue while developing this project, which I've countered with the above headers along with the following in my .htaccess file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Could this potentially be related? Any help/ideas would be greatly appreciated!
The problem appears to have been indeed related to CORS and after trying a multitude of approaches, the following solution is now working.
Replacing my headers in read.php with:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
Credit goes to slashingweapon who used it to answer CORS with php headers
I have this funcion who list objects with arrays:
//onload event-- to set the values
$scope.$on('$stateChangeSuccess', function () {
$scope.cart=sharedCartService.cart;
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
});
I need get all datas and insert all (populate) in a database. I´m using MySQL and PHP.
Thanks.
You create a file let say its called save.php
In that file you will have something like
header("Access-Control-Allow-Origin: *");
Global $db;
$db = new PDO('mysql:dbname=databasename;host=localhost', 'dbuser', 'dbpassword');
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$cart = $request->cart;
$total_qty = $request->total_qty;
$total_amount = $request->total_amount;
}
else {
echo "Not called properly!";
}
$query = $db->prepare("
INSERT INTO yourtable
(cart, total_qty, total_amount)
VALUES
(:cart, :total_qty, :total_amount)");
$query->execute(array(
':cart' => $cart,
':total_qty' => $total_qty,
':total_amount' => $total_amount));
And in your function in Angular (stateChangeSuccess) you make a post request on for example http://localhost:8080/save.php
$http.post(url, data, config)
.then(
function(response){
// success callback
},
function(response){
// failure callback
}
);
I'm trying to do a simple POST from angularjs to a dummy php file to understand how this works.
Here in my angularjs part:
<html ng-app="loginApp">
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var logindata = {username:'abc', password:'abc'}
var loginApp = angular.module('loginApp', []);
loginApp.controller('loginCtrl', function ($scope, $http){
var request = $http({
method: "POST",
url: "http://different-ip/a.php",
data: logindata,
headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(logindata.username + logindata.password),
'Access-Control-Allow-Origin': "*"}
});
request.success(
function( data ) {
$scope.someVariableName = data;
}
);
});
</script>
</head>
<body ng-controller="loginCtrl">
<h2>Angular.js JSON Fetching Example</h2>
<p> {{ someVariableName }} </p>
</body>
</html>
Here is my PHP part (a.php) that resides on http://different-ip
<?php
header("Access-Control-Request-Method: *");
header("Access-Control-Request-Headers: *");
header("Access-Control-Allow-Origin: *");
file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?>
When I execute my angularjs file, the chrome console gives me this error:
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
When I try doing a post to this a.php using Postman, everything works fine. So why is angularjs not allowing it?
I've tried to read about CORS and there is no straightforward answer to how this issue can be resolved (code wise). Can someone please help me out? Thanks in advance.
Added this instead of current headers to my PHP file and now it works! Thanks #Armen for your help!
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
Add this 3 headers at top of a.php instead current ones with if condition
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header( "HTTP/1.1 200 OK" );
exit;
}
file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?>
You can check more about CORS here: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header
Postman works because it is additional browser extension which don't cares about headers policy and don't check it before request.
I am on m.example.com and want to get session from www.example.com
php code (session.php):
<?php
ini_set('session.cookie_domain', '.jeelplus.com');
session_set_cookie_params(0, '/', '.jeelplus.com');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With, Content-Type, Origin, Accept');
//header('Access-Control-Allow-Credentials: true');
session_start();
print_r($_SESSION);
echo('11111111111111111');
exit;
?>
jquery code:
function userIsLoggedIn(){
var logged_in = null;
$.ajaxSetup({cache: false, crossDomain:true, headers: {"X-Requested-With": "XMLHttpRequest"}, xhrFields: { withCredentials: true }})
$.get("http://www.example.com/session.php", {requested: 'foo'}, function (data) {
alert(data);
logged_in = data;
});
}
response:
Array
(
)
11111111111111111
what are the missing steps??
Session is not managed for subdomains. You have to use cookie.