problem while running php artisan route:list with jwt installed - php

I've followed this tutorial
https://tutsforweb.com/restful-api-in-laravel-56-using-jwt-authentication/
and it's working fine,
but when i try to run
php artisan route:list
i get this error ,
Tymon\JWTAuth\Exceptions\JWTException : The token could not be parsed from the request
at F:\My_Projects\Laravel\api-laravel-jwt\vendor\tymon\jwt-auth\src\JWT.php:185
181| */
182| public function parseToken()
183| {
184| if (! $token = $this->parser->parseToken()) {
> 185| throw new JWTException('The token could not be parsed from the request');
186| }
187|
188| return $this->setToken($token);
189| }
Exception trace:
1 Tymon\JWTAuth\JWT::parseToken()
F:\My_Projects\Laravel\api-laravel-jwt\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:223
2 Illuminate\Support\Facades\Facade::__callStatic("parseToken", [])
F:\My_Projects\Laravel\api-laravel-jwt\app\Http\Controllers\ProductController.php:14
Please use the argument -v to see more details.
and i've been trying to get around it, but couldn't succeed, any help?
This is a github Repo with my code:-
https://github.com/Imohamedgabr/laravel-5.7-jwt-starter

in the product controller, in this part:-
public function __construct()
{
$this->user = JWTAuth::parseToken()->authenticate();
}
it calls the parse token, that's why it goes to the jwt auth parse token and fails there.
so while there's no authenticated user provided, it fails.
hope this helps.

Related

How to set up WhatAapp cloud webhook on Laravel PHP framework

I have been trying to set up WhatsApp cloud API on my Laravel MVC project. I'm stuck trying to set up webhook to receive WhatsApp notifications when someone sends a message. The below is my code and it is not simply working giving server error or 405 method not allowed error, in the WhatsApp cloud api side it does not pass the validation point.
API
Route::GET('/webhook' , 'admin\InventoryInvoiceController#webhook')->name('webhook');
Controller
public function webhook() {
if($_SERVER['REQUEST_METHOD']=="GET"){
echo $_GET['hub_challenge']; //respond back hub_callenge key
http_response_code(200);
}else{
$data = json_decode(file_get_contents('php://input'), true);
error_log(json_encode($data)); //print inbound message
}
}
I have added this route to the exception so it's run with the need for CSRF validation. Error received on the Whatsapp API Cloud side:
The callback URL or verify token couldn't be validated. Please verify
the provided information or try again later.
What can I try next?
The problem was that I had not added my route to the CSRF exception which would invalidate the request send by Whatsapp cloud api. Make sure to do that before testing! Below is the code:
public function webhook(Request $request) {
$mode = $request->hub_mode;
$challenge = $request->hub_challenge;
$token = $request->hub_verify_token;
echo $challenge;
}
public function __construct() {
$this->middleware('auth:admin',
['except' => ['webhook', 'webhookpost']]
);

How to send parameter with API in get method

I have to run an API on postmen, the project is based upon Laravel. The endpoint is mention below
`Route::get('order/detail/{order}', 'OrdersController#show');`
here is my order controller function:
public function show(Order $order)
{
dd("ok");
}
I am trying to run API using postmen and receiving 404 error
but when I removed {order} from endpoints, it worked. so my question is how can I run this API on postmen. Any help would be highly appreciable.
With Route::get('order/detail/{order}', 'OrdersController#show');
You must use the endpoint is http://localhost:8082/v3/order/detail/45487.
Not ...order/detail?order=45487
then
public function show($order) //$order is 45487
{
dd("ok");
}

Laravel - Stripe - Ultrahook - Webhook are not caught

I'm using Laravel 5.4 and Laravel Cashier. I would like to be able to catch Stripe webhooks in my localhost:8888
To do so I installed ultrahook and I started it like this
Ultrahook
http://stripe.leococo.ultrahook.com -> http://localhost:8888/stripe/webhook
Laravel routes
Route::post('stripe/webhook', '\Laravel\Cashier\Http\Controllers\WebhookController#handleWebhook');
Stripe Webhook configuration
http://stripe.leococo.ultrahook.com
Problem
When I send a webhook from Stripe I get Test webhook sent successfully
In the terminal ultrahook I get this
[2017-05-31 19:26:04] POST http://localhost:8888/stripe/webhook - 200
But it seems the handleWebhook function is not triggered. It does not stop on a break point neither die('test')
I tried php artisan route:clear php artisan config:clear. I don't know wether it is normal or not, but I do not see anything in the network section in the Chrome Inspector
Add the following line in your .env
CASHIER_ENV=testing
Laravel/Cashier checks if your call to the webhook has a valid event id.
To verify this, eventExistsOnStripe calls back stripe servers with this event id to check its existence.
Here is the main webhook entry point from Laravel/Cashier 7.0:
public function handleWebhook(Request $request)
{
$payload = json_decode($request->getContent(), true);
if (! $this->isInTestingEnvironment() && ! $this->eventExistsOnStripe($payload['id'])) {
return;
}
$method = 'handle'.studly_case(str_replace('.', '_', $payload['type']));
if (method_exists($this, $method)) {
return $this->{$method}($payload);
} else {
return $this->missingMethod();
}
}
isInTestingEnvironment just check whether we are in a testing environnment or not : Thank you Cpt Obvious :)
protected function isInTestingEnvironment()
{
return getenv('CASHIER_ENV') === 'testing';
}

Laravel 5.3 Passport API unauthenticated in Postman using personal access tokens

I have set-up Laravel using passport as per the documentation here: https://laravel.com/docs/5.3/passport
A few people have asked about this using the oAuth implementation but I'm trying to use the personal access tokens not oAuth. One suggestion was to remove the auth middleware but obviously this leaves the application wide open so anyone can make requests.
I have the following route (in routes/api.php):
Route::get('/test', function(){
return 'returned string from test route';
})->middleware('auth:api');
This works if I remove the auth middleware so the route is working correctly but when enabling the auth middleware again I get the following error in postman:
{"error":"Unauthenticated."}
These are the headers being sent via postman:
GET /api/test HTTP/1.1
Host: localhost:8000
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImU4ZmY5MDMwY2EyM2E2MDYwODViN2Y3ZWNiMzcxNDY1MzQxNDViNTk4ODU4NmZhNDljYzU2YjMzYWZiNzhkYTk5OTIwZWMzYzEwNTBkNjZjIn0.eyJhdWQiOiIyIiwianRpIjoiZThmZjkwMzBjYTIzYTYwNjA4NWI3ZjdlY2IzNzE0NjUzNDE0NWI1OTg4NTg2ZmE0OWNjNTZiMzNhZmI3OGRhOTk5MjBlYzNjMTA1MGQ2NmMiLCJpYXQiOjE0NzU1MDMxNjUsIm5iZiI6MTQ3NTUwMzE2NSwiZXhwIjowLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.IpzKK29dJCpliUXQvPRss87kGFngFcXXwV3jRwhbZOZLxl-4UV70cBsSigmqUuBsHQ4onVl_Cjcq6cEmMFvTZZr7D9AtY3EmScvMPjoFh4KQ3wgd5CoyWfcLQgoBxbElNxL0xW2fIQhpeQd_8Yz_Pr5BByGVTpxfg4JJZ4PzovvZsa2R3izYtqw6-qeurQOtsfOnot5uoLDeDDc76klifnfHfOcNZSoIFGNP3gIGKYBe6lfFuDViR_mQkwQS5_UmERt3GSkEvJjGMtwcRjWY7VPAJ4tvWLnyLw0roGU2e37L0wsqfJ8OrG0Cipv-anXAW_utSo-fiVMr8ZeAWIPguq73Zd44x95YY3nNPOKD5dVIRZM7rQgdhjIwTEz1ggtSXLp-Fu3QOtXaHUahCHvjOTdiTYEa-GR4TZ5wGzt-aRhjdBB7WTe0C6T9ZWVwQr0kJk8AxW6ne87wwJYp_shGunTclZ3SCq5VYg2K_MclbJl65-dT8x-nwqg0lqfNx9s1wmtryrMFIPoBEyaGNEK1aWGHKq418-BIQ1_UAhcHHtEXclWvsGWwhyo3aso-E-sCN2o_IkYvSboIsdFAIXvDvQmoAwis6f1J57zWH8AW1ynCFcBgzBDjIyiaCE5nqtb_4zbEXr8L1EbcllbtZkq3vd9w996kO7xlpBEWwPY8IWg
Accept: application/json
Cache-Control: no-cache
Postman-Token: 6bc483b2-23df-acce-7eef-5a443f8f5d45
Firstly, NEVER modify the vendor files unless you have a fully legitimate reason for doing so and there's a feature you wish to see implemented or a bug you've discovered and fixed in the package you're using.
Expiration time on the JWT might be already set to expire as soon as it's made. Here's a link you can use to check the "ttl" (Time To Live) field of your access tokens:
https://jwt.io/
If you find that your tokens are expiring on creation, you can go to your app\providers\AuthServiceProvider.php class and add in these methods on use of Passport Class:
use Carbon\Carbon;
use Laravel\Passport\Passport;
...
Class AuthServiceProvider extends ServiceProvider {
...
...
public function boot() {
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addYears(20));//You can also use addDays(10)
Passport::refreshTokensExpireIn(Carbon::now()->addYears(20));//You can also use addDays(10)
Passport::pruneRevokedTokens(); //basic garbage collector
}
}
Make sure you're using the most recent version of Passport
Currently I'm on version 1.0.8 but I might already be out of date as they and the community are constantly pushing new revisions every few weeks.
Here are links to some related issues regarding this problem. You might be able to locate your answer within one of the below links. If what's mentioned above isn't what you're looking for.
Passport - "Unauthenticated." - Laravel 5.3
Very Detailed
https://github.com/laravel/passport/issues/151
in passport.php there are two functions
public static function tokensExpireIn(DateTimeInterface $date = null)
{
if (is_null($date)) {
return static::$tokensExpireAt
? Carbon::now()->diff(static::$tokensExpireAt)
: new DateInterval('P100Y');
} else {
static::$tokensExpireAt = $date;
}
return new static;
}
/**
* Get or set when refresh tokens expire.
*
* #param \DateTimeInterface|null $date
* #return \DateInterval|static
*/
public static function refreshTokensExpireIn(DateTimeInterface $date = null)
{
if (is_null($date)) {
return static::$refreshTokensExpireAt
? Carbon::now()->diff(static::$refreshTokensExpireAt)
: new DateInterval('P100Y');
} else {
static::$refreshTokensExpireAt = $date;
}
return new static;
}
you must change P100Y to P1Y. and also in PassportserviceProvider.php at line 101 there is code
$server->enableGrantType(
new PersonalAccessGrant, new DateInterval('P100Y')
);
change P100Y to P1Y. hope it helps you :)
Please check if the token was copied properly, i always observed when i copy the personal tokens, in the last there is a word 'Close' copied also.
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImU4ZmY5MDMwY2EyM2E2MDYwODViN2Y3ZWNiMzcxNDY1MzQxNDViNTk4ODU4NmZhNDljYzU2YjMzYWZiNzhkYTk5OTIwZWMzYzEwNTBkNjZjIn0.eyJhdWQiOiIyIiwianRpIjoiZThmZjkwMzBjYTIzYTYwNjA4NWI3ZjdlY2IzNzE0NjUzNDE0NWI1OTg4NTg2ZmE0OWNjNTZiMzNhZmI3OGRhOTk5MjBlYzNjMTA1MGQ2NmMiLCJpYXQiOjE0NzU1MDMxNjUsIm5iZiI6MTQ3NTUwMzE2NSwiZXhwIjowLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.IpzKK29dJCpliUXQvPRss87kGFngFcXXwV3jRwhbZOZLxl-4UV70cBsSigmqUuBsHQ4onVl_Cjcq6cEmMFvTZZr7D9AtY3EmScvMPjoFh4KQ3wgd5CoyWfcLQgoBxbElNxL0xW2fIQhpeQd_8Yz_Pr5BByGVTpxfg4JJZ4PzovvZsa2R3izYtqw6-qeurQOtsfOnot5uoLDeDDc76klifnfHfOcNZSoIFGNP3gIGKYBe6lfFuDViR_mQkwQS5_UmERt3GSkEvJjGMtwcRjWY7VPAJ4tvWLnyLw0roGU2e37L0wsqfJ8OrG0Cipv-anXAW_utSo-fiVMr8ZeAWIPguq73Zd44x95YY3nNPOKD5dVIRZM7rQgdhjIwTEz1ggtSXLp-Fu3QOtXaHUahCHvjOTdiTYEa-GR4TZ5wGzt-aRhjdBB7WTe0C6T9ZWVwQr0kJk8AxW6ne87wwJYp_shGunTclZ3SCq5VYg2K_MclbJl65-dT8x-nwqg0lqfNx9s1wmtryrMFIPoBEyaGNEK1aWGHKq418-BIQ1_UAhcHHtEXclWvsGWwhyo3aso-E-sCN2o_IkYvSboIsdFAIXvDvQmoAwis6f1J57zWH8AW1ynCFcBgzBDjIyiaCE5nqtb_4zbEXr8L1EbcllbtZkq3vd9w996kO7xlpBEWwPY8IWg Copy
If this is not your case check if that token exist, or generate a new one. you can use this format to protect route like this
Route::middleware('auth:api')->get('/home', function(){
return 'test';
});
I Had this problem ... two hours down the pan. Something very strange was happening and in my case I think Postman was the culprit.
Inspect the received header to rule it out:
Route::get('/test', function(){
dd( Request::header());
})/*->middleware('auth:api')*/; //disable auth middleware to inspect header
this is the strange thing I found:
.........
"authorization" => array:1 [
0 => b"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJ ................
what the hell was the 'b' before Bearer ACCESS_TOKEN ???
I typed it out again and it dissapeared and auth middleware started working.
Inspect the header exactly and then add the middleware back. This might just be the cause!

Auth component in Cakephp 3.0

I have a free installed instance of Cakephp 3.0 with several code examples, everything is working fine. Now I want to create a Auth component in ./src/Auth, concerning the documentation here
Thats my code:
<?php
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
class AlephAuthenticate extends BaseAuthenticate
{
public function authenticate(Request $request, Response $response)
{
// Do things for OpenID here.
// Return an array of user if they could authenticate the user,
// return false if not.
}
}
In AppContoller.php I initialize this component:
public function initialize() {
$this->loadComponent('Auth');
$this->Auth->config('authenticate', ['Aleph']);
}
Calling the application URL in the browser shows:
Fatal error: Declaration of App\Auth\AlephAuthenticate::authenticate() must be compatible with Cake\Auth\BaseAuthenticate::authenticate(Cake\Network\Request $request, Cake\Network\Response $response) in /var/www/art/src/Auth/AlephAuthenticate.php on line 7
Any idea whats wrong here?
Thanks!
Christoph
Please read the error message it is obvious. If you still have trouble understanding it just paste the error message into a search engine. This is the basic procedure for almost every error message if you don't know it and will probably always solve it. Guess it's in the php documentation as well.
Let me rephrase the error message for you: The method signatures don't match. To get rid off the error message make them match.

Categories