Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::withHeaders() - php

i was trying to download and this bug came out and i don't how to fix it!
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class XFrameHeaders
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->withHeaders([
'X-Frame-Options' => 'DENY',
'X-XSS-Protection' => '1; mode=block',
'X-Permitted-Cross-Domain-Policies' => 'master-only',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'no-referrer-when-downgrade',
'Strict-Transport-Security' => 'max-age=31536000; includeSubDomains',
'Cache-Control' => 'no-cache, no-store, must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'no-cache',
'Expires' => 'Sat, 26 Jul 1997 05:00:00 GMT',
]);
return $response;
}
}
this is the code that got pop-up on my screen and don't have the knowledge to fix it!
also the error line is number 20

The withHeaders does not exist in the response object which is an instance of Symfony\Component\HttpFoundation\BinaryFileResponse.
To fix this error, you can replace withHeaders with headers->set() which does not accept an array of headers so you have to set each header in one line.
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('X-XSS-Protection', '1; mode=block');
$response->headers->set('X-Permitted-Cross-Domain-Policies', 'master-only');
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('Referrer-Policy', 'no-referrer-when-downgrade');
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate, post-check=0, pre-check=0');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');

Related

Laravel v8.15.0 (PHP v7.3.23) An API for Mobile Application on a Shared Server POST Routes not working

I'm on Shared Server.
Laravel v8.15.0 (PHP v7.3.23)
unable to set it up properly.
Sanctum & Passport both tried but that crashes with 500 Internal Server Error. So removed them.
https://townies.pk/api/v1/getCart is working.
Another GET route for fetching Images is also working.
But https://townies.pk/api/register POST or https://townies.pk/api/v1/register POST not working. 500 Internal Server Error.
And https://townies.pk/api/login POST or https://townies.pk/api/v1/login POST not working. 500 Internal Server Error.
api.php
<?php
use App\Models\User;
use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/*Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});*/
Route::get('/v1/getCart', function(Request $request){
return response()->json([
'success'=> true,
'msg'=> "yes",
'cartItems' => ['Beef Salaami Large: Rs. 780/-', 'Chicken Supreme Small: Rs. 290/-', 'Super Supreme Medium: Rs. 530/-' ]
])
->header('Content-Type', 'application/json');
});
Route::post('/v1/register', [AuthController::class, 'register'])->name('register');
Route::post('/v1/login', [AuthController::class, 'login'])->name('login');
AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
if($validator->fails())
{
Log::error('Something is really going wrong.');
return response()->json(['status_code' => 400, 'message' => 'Bad Request']);
}
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = algo($request->password);
$user->save();
return response()->json([
'status_code' => 201,
'message' => 'User Registration Successful.'
]);
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required'
]);
if($validator->fails())
{
return response()->json(['status_code' => 400, 'message' => 'Bad Request']);
}
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
{
return response()->json([
'status_code' => 401,
'message' => 'Unauthorised'
]);
}
$user = User::where('email', $request->email)->first();
$tokenResult = $user->createToken('authToken')->plaitTextToken;
return response()->json([
'status_code' => 200,
'token' => $tokenResult
]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json([
'status_code' => 200,
'message' => 'LogOut Successful'
]);
}
}
My Database Schema
Next time, please share the exception message from your logs. It is much easier and faster to debug errors when we have a clear picture on the error message itself.
I tried with Laravel Sanctum and /register works fine after adding the missing imports to AuthController and HasApiTokens trait to User model, as outlined below.
/login was still failing until fixing a typo on this line:
$tokenResult = $user->createToken('authToken')->plaitTextToken;
plaitTextToken is misspelled. Should be: plainTextToken.
These are the imports missing on AuthController:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
Also, be sure to:
Add the Laravel\Sanctum\HasApiTokens trait to the User model
Add the middleware needed for Sanctum into ./app/Http/Kernel.php under the api middleware group
Publish and run Laravel Sanctum migrations
All these are outlined on Laravel Sanctum installation guide, please be sure to follow the installation guide very closely:
https://laravel.com/docs/8.x/sanctum#installation
After applying the changes above I tried with PHPStorm HTTP Client using these requests:
POST http://my-app.test/api/v1/register
Accept: application/json
Content-Type: application/json
{"name": "bar", "email": "bar#example.com", "password": "password"}
###
POST http://my-app.test/api/v1/login
Accept: application/json
Content-Type: application/json
{"email": "bar#example.com", "password": "password"}
###
With these corresponding responses:
POST http://my-app.test/api/v1/register
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache, private
Date: Sun, 29 Nov 2020 01:26:22 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Access-Control-Allow-Origin: *
{
"status_code": 200,
"message": "User Registration Successful."
}
Response code: 200 (OK); Time: 80ms; Content length: 61 bytes
And
POST http://my-app.test/api/v1/login
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache, private
Date: Sun, 29 Nov 2020 01:27:17 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
Access-Control-Allow-Origin: *
{
"status_code": 200,
"token": "1|5ImkzdVQgNhQyotxlZzs5Hr2YDkTPKfpfovthx1o"
}
Response code: 200 (OK); Time: 86ms; Content length: 72 bytes

react to Laravel -- Cors Middleware NOT working

tried lots of things as in other solutions
in route.php
header('Access-Control-Allow-Origin: http://www.campaignpulse.com/');
or
header('Access-Control-Allow-Origin: www.campaignpulse.com/');
or
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization');
Route::post('cors', ['middleware' => 'cors',function () { return response()->json(['message' =>'cors'], 200); } ]);
cors.php
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', 'http://www.campaignpulse.com/')
or
->header('Access-Control-Allow-Origin', 'www.campaignpulse.com/')
or
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization');
}
kernal.php
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Cors::class,
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'cors' => \App\Http\Middleware\Cors::class,
];
react part
return fetch('http://www.campaignserver.com:81/cors',
{
method: 'post',
credentials: "same-origin",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'www.campaignpulse.com' },
}
).then(response => response.json())
.then(resData => {
console.log(resData)
})
and the error is
Access to fetch at 'http://www.campaignserver.com:81/cors' from origin 'http://www.campaignpulse.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
what else can i try ? please suggest
Cross origin requests made by a browser will send a pre-flight OPTIONS request to your server, which has to return at least the Access-Control-Allow-Origin header.
It is not sufficient to just return it with the response to a POST route.
I recommend to use a package like https://github.com/barryvdh/laravel-cors to provide the CORS middleware and configuration
Also notice that the origin is a host name or a wildcard.
Valid values for the ACAO header are for example
*
https://www.example.org
No URI parts
edit
have to correct myself, apparently protocol and port are valid parts of the ACAO header, which makes sense
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
edit2
To debug this, make sure that both
OPTIONS http://www.campaignserver.com:81/cors
and
POST http://www.campaignserver.com:81/cors
Return a header
Access-Control-Allow-Origin: http://www.campaignserver.com:81
or
Access-Control-Allow-Origin: *

Laravel appending extra data along with custom response in controller

I am calling a function which is in my laravel controller. I have used laravel's custom response to return data. But some other data is getting added to my response even though I have not added it.
return Response::make(json_encode(array(
'error' => false,
'message' => 'Redaction done successfully.',
'is_redacted' => 0)), 200,
array(
'Content-Type' => 'application/json'
)
);
Above is the code that I have added to return my response.
But response that I am receiving is:
> * Found bundle for host redaction-stage-tcm.tylerhost.net: 0x55998c67ee40
* Re-using existing connection! (#0) with host redaction-stage-tcm.tylerhost.net
* Connected to redaction-stage-tcm.tylerhost.net (208.64.239.110) port 443 (#0)
> POST /ocr/OCRWeb/v2/Documents('mfr_8')/OCRWeb.Scan HTTP/1.1
Host: redaction-stage-tcm.tylerhost.net
User-Agent: GuzzleHttp/6.3.3 curl/7.43.0 PHP/5.6.11-1ubuntu3.4
OData-Version: 4.01
OData-MaxVersion: 4.01
Content-Type: application/json
Content-Length: 2
upload completely sent off: 2 out of 2 bytes
< HTTP/1.1 200
< Cache-Control: no-transform
< Cache-Control: no-cache
< Cache-Control: no-store
< Cache-Control: must-revalidate
< Cache-Control: max-age=0
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Vary: *
< Pragma: no-cache
< X-Clacks-Overhead: GNU Terry Pratchett
< OData-Version: 4.01
< Preference-Applied:
< Content-Type: application/json; odata.metadata=minimal
< Content-Length: 163
< Date: Wed, 13 Feb 2019 10:44:40 GMT
<
* Connection #0 to host redaction-stage-tcm.tylerhost.net left intact
{"error":false,"message":"Redaction done successfully.","is_redacted":0}
I have called some rest APIs in my function. This data is related to that but why is it getting appended to my custom response??
Please help me with it.
Try this,
return response()->json([
'error' => false,
'message' => 'Redaction done successfully.',
'is_redacted' => 0,
'Content-Type' => 'application/json'
], 200)
create a Middleware called AddToRequest and registered it in Kernel.php. See the code below
AddToRequest.php
<?php namespace App\Http\Middleware;
use Carbon\Carbon;
use Closure;
class AddToRequest {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$request->request->add(['dummy' => 'hey man', 'date' => Carbon::now()]);
return $next($request);
}
}
Kernel.php
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
];
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'inject' => 'App\Http\Middleware\AddToRequest'
];
}
In the handle() method of the AddToRequest Middleware, I set two variables and add it to the request
$request->request->add(['dummy' => 'hey man', 'date' => Carbon::now()]);
Then, in my controller I use the inject middleware
public function __construct()
{
$this->middleware('inject');
$this->middleware('guest');
}
In the index() method of the controller I inject the use Illuminate\Http\Request object and pull the variables I set in the middleware from the request object as follows:
public function index(Request $request)
{
dd($request->get('dummy'), $request->get('date'));
return view('welcome');
}

CORS Middleware in Dingo API in Laravel

I want to apply cors in dingo api in laravel.
Because, I am getting this error.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 500.
I have tried this.
Created Cors middleware.
Added like this Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials',' true');
}
}
Then modified Kernel.php like this.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \App\Http\Middleware\Cors::class,
];
Now, I want to know how to add middleware in dingo api routes.
Routes are like this.
$api->version('v1', function($api){
$api->GET('statelist', 'App\Http\Controllers\HospitalController#statelist');
});
$api->version('v1', function($api){
$api->GET('citylist', 'App\Http\Controllers\HospitalController#citylist');
});
try
$api->version('v1', function ($api) {
$api->group(['middleware' => 'cors'], function ($api) {
$api->GET('statelist', 'App\Http\Controllers\HospitalController#statelist');
$api->GET('citylist', 'App\Http\Controllers\HospitalController#citylist');
});
});

How to solve CORS error in api (implemented using Lumen) while testing using Swagger UI

I am facing a CORS error while firing an API created using Lumen via Swagger UI eated. So I created a middleware to solve this CORS problem:
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
And used this middleware in my route for that API, now after using this my corse error problem solved but API is not working properly, throwing an error for the below code:
//**** code that throwing error starts ****
$config = app()->make('config');
$data = array_merge([
'client_id' => $config->get('secrets.client_id'),
'client_secret' => $config->get('secrets.client_secret'),
'grant_type' => $grantType,
'username' =>$data['username'],
'password' =>$data['password']
], $data);
$http = new Client();
$headers = ['Content-Type' => 'application/json'];
$guzzleResponse = $http->post( $config->get('app.url').'/oauth/token', [
'form_params' => $data,
]);
$tokenDetails = json_decode($guzzleResponse->getBody(),true);
//************** Code throwing error ends ******
Now when I remove the middleware from route the API is working fine with POSTMAN but throwing CORS error for SWagger, and when I use the middleware for solving CORS problem, API is not working properly.
Add this line in .htaccess
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
after RewriteEngine On line

Categories