I have a Laravel project that i recently tried to set in my local environment.
The project is REST-API based, and all of the requests are made with API.
When i try to send an API request to my local environment project i get UnauthorizedRequestException.
Since i am not fully familiar with Laravel i couldn't tell where do i set the authentication.
I tried to trace the error but all i get is a bunch of functions that do not help me. or at least that's what i think because non of them shows where i can find the authentication settings.
This is the error i get in the browser when i try to send an API request:
{
success: false,
errors: "Not Authorized",
data: null
}
This is an error that was set up in case of unauthorized access and the code for it is:
App::error(function(UnauthorizedRequestException $exception, $code)
{
$headers = array(
'Access-Control-Allow-Origin' => '*',
);
return Response::json(
array(
'sucess' => false,
'errors' => $exception->getMessage(),
'data' => null,
),
$exception->getCode(),
$headers
);
});
This code is located in app/start/global.php.
If someone knows where i can set the authentication so i can start working on my local environment let me know. Thanks.
Related
we are getting this 500 error but only in prod environment. This app works fine in DEV/QA env
Even in prod this app works fine until you send a form to edit some data in data base. Then, when
debuggin I realized that this error occurs here:
return new JsonResponse(
array(
'message' => $message,
'form' => $this->renderView(
$template,
array(
'cv' => $cv,
$formName => $form->createView(),
)
),
'view' => $view
),
$code
);
apparently the path for the template in $view not exist. But it makes no sense because it does exists, even the app calls this template in other context and just works fine.
My english is not good so I hope you can understand me. Thank you!
EDIT: Symfony and server error logs has been already checked, but found nothing about this error.
Hi I'm trying to get a token from an api but no matter what I try on the droplet I get an invalid client every single time, the code is the same locally and on the droplet, currently working on local but not on the droplet.
This is the code
return Cache::rememberForever('payment_token', function () {
$client = new Client(['http_errors' => false]);
$params = [
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'grant_type' => 'client_credentials',
];
$headers = [
'Accept' => 'application/json',
];
$response = $client->request('POST', 'https://apipay.io/auth/token/', [
'json' => $params,
'headers' => $headers
]);
$res_body = json_decode($response->getBody()->getContents());
return $res_body->access_token;
});
The url for the post isn't a real one, I don't really think it's wise to post the real one as it doesn't work without the client_id and client_secret which I can't post here.
Is there a reason why the droplet would interfere with this? What can I do to fix this?
Double-check the remote .env file and make sure, that it's not some outdated, cached version of it (which env() would then return). Laravel has this feature, which can indeed be quite tricky, while not considering that (eg. it just doesn't work for no apparent reason). php artisan cache:clear clears the config-cache and php artisan config:cache builds it up again; I even think that production uses a cached config by default (which may be the actual difference there).
Good morning, everyone,
As part of the development of demonstration APIs, I realized two APIs :
HelloWorld
Notify
The first one allows to ask for a HelloWorld to be performed, the second one allows to send e-mails according to defined templates.
In my demonstration I make from Postman (or from a React application) an API call to HelloWorld which then makes an API call to Notifier to send the message.
If from Postman I call directly my Notifier API to send an email, I do not encounter any problem (the .env file is well configured for sending emails in this API).
On the other hand if I call my API from HelloWorld to Notifier (the .env file of HelloWorld is not configured for sending e-mails), I encounter an error:
Expected response code 250 but got code "530", with message "530 5.7.1
Authentication required
On the other hand if I configure the .env file of the HelloWorld API (which does not send an e-mail at any time), I do not have any more error and my e-mail is well sent by Notifier.
This is the API Call in HelloWorld :
$client = new Client();
$response = $client->post("http://vhost-url.local/api/notifier/sendmail", [
'json' => [
'to' => $to,
'template' => $template,
'parameters' => $parameters
],
]);
And this is the action called in Notifier API :
public function sendmail(Request $request)
{
$params = json_decode($request->getContent(), true);
try{
switch ($params['template']) {
case 'HELLO_WORLD':
Mail::to($params['to'])
->send(new HelloWorld([
'message' => $params['parameters']['message']
]));
break;
default:
throw new \Exception("Ce template n'existe pas");
break;
}
} catch(\Exception $e) {
return response()
->json([
'message' => $e->getMessage(),
], 500);
}
return response()
->json([
'message' => 'Le mail a bien été envoyé'
], 200);
}
My question is: During an API call (with Guzzle in my case), is the environment file of the source API used instead of the environment file of the destination API? And if so, how to fix this problem?
I'm not sure if this helps but I have had similar problems. The .env files get messed up when cross-communicating Laravel projects (on Windows only I believe).
See for instance https://github.com/laravel/framework/issues/19454 .
The solution is to run php artisan config:cache to create a cached version of your .env variables. Note that you should never use env('...') in your code, instead you should refer to them using a config file like config('app.env'). .env variables can not be dynamic for this reason.
For custom env variables, I usually create a config/project.php file like so:
return [
'my_custom_var' => env('PROJECT_MY_CUSTOM_VAR')
];
That way you can cache it and call the variable using config('project.my_custom_var');
Environment
I created an application using Laravel 5.7 and implemented a REST API. I have a route in routes/api.php that triggers a middleware which checks if the incoming request has a parameter called api_token.
This is a production environment and here are the specifics:
Linux Ubuntu 18.04 LTS 64-bit
nginx/1.14.0
Laravel 5.7
PHP 7.2
APP_ENV in the .env file is set to 'production' and APP_DEBUG is set to 'false'.
Problem
My problem is that the incoming request object is always empty when it arrives at the server. At least that's what my Laravel application says.
These are my routes in routes/api.php:
Route::middleware('rest')->group(function() {
Route::get('device-location/{deviceID}', 'PositionDataController#getDeviceLocation');
Route::get('device-location/all', 'PositionDataController#getAllLocations');
Route::post('device-location', 'PositionDataController#storeDeviceLocation');
Route::put('device-location/{deviceID}', 'PositionDataController#updateDeviceLocation');
Route::delete('device-location/{deviceID}', 'PositionDataController#deleteDeviceLocation');
});
The routes are in a middleware group called 'rest' as you can see. I'm using the Route::get('device-location/{deviceID}', 'PositionDataController#getDeviceLocation'); route to test the functionality.
Here's the code from the middleware:
public function handle($request, Closure $next)
{
if(request()->all()) {
$deviceID = request()->device_id;
}
else {
return response()->json([
'error' => 'The request object is empty.',
'request' => request(),
'parameters' => request()->all(),
'content' => request()->getContent(),
'input' => request()->input()
], 500);
}
$device = MobileDevice::where('device_id', $deviceID)->first();
if($device) {
$deviceToken = $device->api_token;
if($deviceToken == request()->api_token) {
return $next($request);
}
else {
return response()->json(['error' => 'Token does not match.'], 500);
}
}
else {
return response()->json(['error' => 'The device with the id [' . $deviceID . '] could not be found.'], 500);
}
}
The middleware first checks if there are parameters in the request object and then does some logic to check if the right token was sent. If the request object is empty it returns some data to help me understand what went wrong.
I use Postman (https://www.getpostman.com) to test the API. Here's my Postman setup:
Postman setup
Postman headers
This is the response I get in Postman:
Postman response
I get the same result if I call that route in a browser.
Regardless of if I put in parameters or not the request seems to be always empty.
Here are the things that I've tried to do:
Not using the middleware
Using the $request variable instead of the helper request()
Switching between 'application/json' and 'application/x-www-form-urlencoded' in the Headers of my Postman setup
Calling that route in a browser
Updating to Laravel 5.7
The strange thing is that all of this works perfectly on my local environment and on a test server that has the same specs as the production server.
UPDATE 01:
So it seems to be even worse...
If I add a route like this in web.php:
Route::get('/request-return', function() {
return request()->all();
});
and visit that route like this:
laravel.application/request-return?device_id=1&api_token=XgkQLs8G7OYTqdwsXmjJT5G9bxv20DRi
I get back an empty array [].
So it seems like the parameters don't get to the server itself.
You are getting device id through GET request so use the below line instead of $request()->device_id.
Use this and let me know
$name = $request->input('device_id')
Okay I could solve the problem. It didn't have anything to do with Laravel. It was a nginx configuration problem:
https://serverfault.com/questions/231578/nginx-php-fpm-where-are-my-get-params
I'm trying to send an email to all the users in the database, but I'm getting the following error: [GuzzleHttp\Exception\ClientException] Client error: 400.
Here's my code:
$users = App\User::all();
foreach($users as $user) {
$code = new App\Code();
$code->code = str_random(10);
$code->save();
Mail::send('emails.code', ['code' => $code], function($message) use ($user)
{
$message->to($user->email)->from('foo.bar#gmail.com', 'Foo Bar')->subject('New code, new chances!');
});
}
[GuzzleHttp\Exception\ClientException] Client error: 400
is for URL not found
Check for host url in config/mail.php, host url might be wrong
Not sure if you have got it working but I had the exact same problem today and I had no idea what went wrong as I did the exact same implementation just in my previous Laravel project with mailgun. Then I found the issue in the configuration.
So, here is the glitch..I don't know in which version it was changed, but in config/services.php the mailgun config is now like this,
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
where it was like this before as far as I can remember,
'mailgun' => [
'domain' => env('MAIL_DOMAIN'),
'secret' => env('MAIL_SECRET'),
],
so in my .env file, I was only referencing MAIL_DOMAIN and MAIL_SECRET environment variables but I just realised in the services.php file, it's actually referencing different environment variables - MAILGUN_DOMAIN and MAILGUN_SECRET.
So I've just added these environment variables, cleared the config cache and it is working perfectly now.
(I am working with Laravel 5.1.23 version BTW)
Hope this helps. Thanks.