Laravel 5.3 + Passport: always unauthenticated error - laravel-5.3

I'm always receiving "Unauthenticated error" when using Passport in my current project. That's what I did the lasts 3 days:
Install and configure Passport (as docs says)
Request a token (password grant token) with Postman
Request a protected route (auth:api middleware) with the token
Get
`{ "error": "Unauthenticated." }`
Search and search and research
Get
`{ "error": "Unauthenticated." }`
Then, I've installed a fresh L5.3 and a fresh DB and works fine. Even with my current DB!
I've tried all the solutions that I found without success ...
Can anyone help me? Any idea would be appreciated.
Thanks.

I had the same problem as you and looked everywhere to find a solution.
It appeared to be Apache's fault in my case. Apache was deleting the header "Authorization: Bearer TOKEN_HERE" so the auth:api wouldn't work as expected (getting 401 unauthorized).
We ended up trying adding to our .htaccess:
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
And it magically worked.
I really hope it helps, we spent a whole day trying many solutions, this is the one that worked for us.

Which grant_type have you used to generate this token?
Possible resolutions are as follows
1: If you are using client credentials to generate your access_token, you have to turn on client_credentials, middleware as follows.
1.1 Add to the routeMiddleware in \App\Http\Kernel.php
'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
1.2 Use 'client_credentials' middleware in your route too.
Route::group(['prefix' => 'v1','middleware' => 'client_credentials'], function () {
// Your routes here
});
2: For Grant Type Password
2.1 : Create a Password Grant Client
php artisan passport:client --password
2.2 : Request A token with following header fields
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'taylor#laravel.com',
'password' => 'my-password',
End point /oauth/token
The token you get now should give you access to your api.

My problem was an omision, I'm building a GraphQL api and in the middleware line at the configuration file "graphql.php" I put
'middleware' => ['auth'],
when the correct way is:
'middleware' => ['auth:api'],

check your user model has
use Laravel\Passport\HasApiTokens;
instead of
use Laravel\Sanctum\HasApiTokens;
and used HasApiTokens as a trait;

Related

Github Probot create-probot-app: 'Cannot POST /' (404) response to webhook request

Testing out the npx create-probot-app; tried with each of the starters and the same problem exists.
I create, build, and run the app, and then configure and install the app on github, I am able to receive webhook events but I'm seeing my local app respond with a 404.
smee receives the event
error: Error: cannot POST / (404)
ERROR (server): Not Found
Error: Not Found
at Request.callback (/Users/X/Projects/Y/compiler/githubapp/x-bot/node_modules/superagent/lib/node/index.js:884:15)
at IncomingMessage.<anonymous> (/Users/X/Projects/Y/compiler/githubapp/x-bot/node_modules/superagent/lib/node/index.js:1127:20)
at IncomingMessage.emit (events.js:326:22)
at IncomingMessage.EventEmitter.emit (domain.js:483:12)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
status: 404
My index.ts:
export = (app: Probot) => {
app.on("issues.opened", async (context) => {
const issueComment = context.issue({
body: "Thanks for opening this issue!",
});
await context.octokit.issues.createComment(issueComment);
});
// For more information on building apps:
// https://probot.github.io/docs/
// To get your app running against GitHub, see:
// https://probot.github.io/docs/development/
};
I've checked that my environment variables appear to be setup correctly in .env
In sum, github is sending a webhook, smee is receiving it, but my local app is responding with 404: cannot post /
Not able to get the example app to process webhook events due to what appears to be a routing issue. Anyone encountered this before?
Make sure you don't have any other applications running on Port 3000. Create React App uses 3000 by default and can cause the error you are describing.
One of the possible reasons could be that your GitHub App does not have privileges to take that action. Would it be possible that your GitHub App is missing the 'issues' privilege setting? (https://docs.github.com/en/rest/reference/permissions-required-for-github-apps#permission-on-issues)

NextJS/Image: "url" parameter is valid but upstream response is invalid

I am trying to fetch images from Strapi into my NextJS Application, but whatever I am trying to do I am always getting the error
"url" parameter is valid but upstream response is invalid"
The console is stating:
Failed to load resource: the server responded with a status of 400
(Bad Request)
I already updated "next" to the latest version:
Here is my Snippet from my Image Code:
What else can I try to not receive an error anymore?
I think you didn't add the source to your image domain, probably you should read more on the Image docs here https://nextjs.org/docs/api-reference/next/image
To get rid of this error, create a 'next.config.js' file in the root of your project. Add Domain of all images except local host to the domains array, like so:
module.exports = {
reactStrictMode: true,
images: {
domains: [
"platform-lookaside.fbsbx.com", //facebook
"firebasestorage.googleapis.com", //firebase-storage
"scontent-atl3-2.xx.fbcdn.net", //facebook
"pbs.twimg.com", //twitter
],
},
};
So in your case since, you're fetching from an external source, don't include 'localhost'
May it help someone, I had this issue because I had changed the names of the properties of the response object received from the api from its default case (snake_case) to camelCase while generating a typescript type for it.

Stripe payment ssl protocol error WordPress

We have used stripe payment using PHP. It works on the local machine but in live server, it's not worked as expected. We shared the code which we used and also attached the screenshot of the error. Not sure where we made the mistake, can you guide us?
Stripe Code :
require_once('Stripe.php');
Stripe::setApiKey('secret key');
echo '<form action="" method="post">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="publish key"
data-description="Access for a year"
data-amount="5000"
data-locale="auto"></script>
</form>';
if($_POST) {
$token = $_POST['stripeToken'];
$customer = Stripe_Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => 5000,
'currency' => 'usd'
));
echo '<h1>Successfully charged $50.00!</h1>';
}
Local Machine
Live Server
1) It looks like potentially you haven't copied the data folder that comes with the stripe php bindings over to your server --- this contains the ca-certificates.crt file referenced in the failed loading cafile error. Make sure this folder is present on your server and see if that resolves the issue!
2) If you continue to have trouble the issue may involve an inability of your server to communicate over TLS 1.2 to Stripe. From your syntax it looks like you are using an older version of Stripe's PHP library so you'll want to use the second sample here to test that.
You can also run a test script like this to help determine your libcurl and openssl versions, if curl is able to make TLS 1.2 connections in the first place. If you need to upgrade curl and openssl some helpful advice is here. You can also chat with your sysadmin or web host on the matter.

How to make SQLite work in Laravel

Whenever I run php artisan migrate, the following error is shown in the console:
[PDOException]
SQLSTATE[HY000] [14] unable to open database file
The database.sqlite file is located at database/. I'm running Windows 10, Laravel 5.2. Here is .env file config:
.env:
DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME=homestead
DB_PASSWORD=secret
I have looked everywhere, but could not find what causes this error and how to resolve it.
Update
I managed to make migrations run successfully by replacing DB_DATABASE=database with DB_DATABASE=database/database.sqlite in .env file. However, new error occurs whenever I try to retrieve items from the database:
public function index()
{
// cause of the error
$cards = Card::all();
return view('cards.index', compact('cards'));
}
The above action throws following error:
InvalidArgumentException in SQLiteConnector.php line 34:
Database (database/database.sqlite) does not exist.
The strange thing is, that the command Card::all() works flawlessly in php artisan tinker mode. What kind of magic is that?
Anyway, I've also found out, that the line:
'database' => env('DB_DATABASE', database_path('database.sqlite')),
in database.php file needs to be replaced with just database_path('database.sqlite') and everything starts to work normally.
It seems, that the root of the problem is env('DB_DATABASE') call. I went to SQLiteConnector.php file and dumped the output of both env('DB_DATABASE') and database_path('database.sqlite'). Here are their outputs respectively:
dd(env('DB_DATABASE')) // => 'database/database.sqlite'
dd(database_path('database.sqlite')) // => 'D:\www\project\database\database.sqlite'
As you see, their output differs, and the second one is what is expected. Is this a Laravel bug? Or did I misunderstood something?
Short Solution
Though not answering the question, the way to fix "Database not found" issue is to replace the following line in database.php:
'database' => env('DB_DATABASE', database_path('database.sqlite')),
with
'database' => database_path('database.sqlite'),
By using the relative path, migrations will fail because they use project directory as root directory...
To correct everything, I suggest setting:
DB_DATABASE=database\database.sqlite
and tweaking the sqlite connections in config/database.php as follows:
'database' => env('DB_DATABASE/..', database_path('database.sqlite')),
Original Answer
The .env file should contain this:
DB_DATABASE=..\database\database.sqlite
With some testing you can verify that the link included in DB_DATABASE
is relative to the 'public' directory (at least on my Windows machine). That's why we should introduce ..\ before your link.
And of course, using an absolute link should do it too:
DB_DATABASE=D:\www\project\database\database.sqlite
as #Josh suggests
Create file called database.sqlite in this folder as database/database.sqlite
Open the .env file and change MySQL to SQLite
Comment password and username and databaseName using '#'
run php artisan migrate enjoy
env file like this:
DB_CONNECTION=sqlite
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=database
#DB_USERNAME=homestead
#DB_PASSWORD=secret
Complementing the awnser by our friend #alexander-lomia
Change:
'database' => env('DB_DATABASE', database_path('database.sqlite'))
To:
'database' => database_path(env('DB_DATABASE'))
in database.php
:)
Instead of a relative path you need to use an absolute path in your .env file.
DB_DATABASE=/var/www/project/database/database.sqlite
or in your case:
DB_DATABASE=D:\www\project\database\database.sqlite
I got the same problem as you did. You have to use the absolute path in ENV file.
Please check the official documentation about this https://laravel.com/docs/5.4/database
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
This worked for me in Laravel 5.5
In .env file just have the connection name and remove all other DB_ related settings: DB_CONNECTION=sqlite_testing
Define your sqlite settings in the config/database.php file:
'connections' => [
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => database_path('testing-db.sqlite'),
'prefix' => '',
],
...
]
My file is in the database/testing-db.sqlite.
Shortest and easiest solution is to remove default mysql settings in .env and work in database.php. That's what worked for me at least.
Remove the following...
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
I found the following works rather well, if you prefer to use relative paths:
replace the 'database' line under SQLite with the following:
'database' => database_path(env('DB_DATABASE', 'database.sqlite')),
This was the setting I had used,
'sqlite' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
I also had to run touch database.sqlite in the database folder.
The problem is that php artisan migrate will use the DB_DATABASE from the root of the project, while serving the project with php artisan serve will run from the public directory.
The best solution for me is to create a link to database inside public directory:
UNIX: ln -s database public/database
Windows: mklink /J public\database database
Of course then you would have to deny access to database folder from HTTP requests but that should be easily done.

Ajax error in draggableviews

We're trying to sort a view with draggableviews 7.x - 2.0 but when attempting to save the we get the following error:
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/structure/views/ajax/preview/jnytt_modul_nyhetsslider/panel_pane_2/387
StatusText: error
ResponseText: PDOException: SQLSTATE[HY000]: General error: 1364 Field 'nid'
doesn't have a default value: INSERT INTO {draggableviews_structure} (view_name,
view_display, args, entity_id, weight) VALUES (:db_insert_placeholder_0,
:db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4); Array
(
[:db_insert_placeholder_0] => jnytt_modul_nyhetsslider
[:db_insert_placeholder_1] => panel_pane_2
[:db_insert_placeholder_2] => ["387"]
[:db_insert_placeholder_3] => 9988
[:db_insert_placeholder_4] => 0
)
Anyone else who have had this problem and found a solution because I sure as h*** can't find one :(
It seems that your db table draggableviews_structure has a field nid that needs a default value. This is outdated because the version 2.x of draggableviews uses entity_id instead. Maybe you upgraded from 1.x to 2.x which is not possible.
There is no upgrade path from 7.x-1.x to 7.x-2.x branch
http://drupal.org/project/draggableviews
So either reinstall to module or edit the database table manually. I would suggest reinstalling via devel

Resources