CTO / Software Architect at Agent Quote

Member Since 2 Years Ago

Experience Points
26,410
Total
Experience

3,590 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
258
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 6
26,410 XP
Dec
11
1 month ago
Activity icon

Started a new Conversation Laravel 8 - Passport - User Login Issuing Access Token - Help

Installed Laravel Passport and Setup Signup/Login below

When I hit the http://localhost:8000/api/auth/login endpoint to login using same credentials as signup, I get the error, listed at the end of this document. Please advise :)

routes/api.php


Route::namespace('Api')->group(function() {

    Route::prefix('auth')->group(function() {

        Route::post('login', [\App\Http\Controllers\Api\AuthController::class, 'login']);
        Route::post('signup', [\App\Http\Controllers\Api\AuthController::class, 'signup']);

    });

    Route::group([
        'middleware' => 'auth:api'
    ], function() {
        Route::get('helloworld', [\App\Http\Controllers\Api\AuthController::class, 'index']);
    });

});

App\Http\Controllers\Api\AuthController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PassportUser;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{

    const SIGNUP_NAME_FIELD_VALIDATION = 'required|string';
    const SIGNUP_FIELD_VALIDATION = 'required|string|email|unique:users';
    const EMAIL_VALIDATION = 'required|string|email';
    const SIGNUP_FIELD_PASSWORD_CONFIRMED_VALIDATION = 'required|string|confirmed|min:16';
    const PASSWORD_VALIDATION = 'required|string|min:16';

    public function index(): string
    {
        return 'Hello Api';
    }

    protected function generateAccessToken($user)
    {
        $token = $user->createToken($user->email.'-'.now());

        return $token->accessToken;

    }

    public function signup(Request $request): \Illuminate\Http\JsonResponse
    {
        $request->validate([
            'name' => self::SIGNUP_NAME_FIELD_VALIDATION,
            'email' => self::SIGNUP_FIELD_VALIDATION,
            'password' => self::SIGNUP_FIELD_PASSWORD_CONFIRMED_VALIDATION
        ]);

        $user = PassportUser::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        return response()->json([
            "message" => "User registered successfully",
            "user" => $user
        ], 201);
    }

    public function login(Request $request): \Illuminate\Http\JsonResponse
    {
        $credentials = $request->validate([
            'email' => self::EMAIL_VALIDATION,
            'password' => self::PASSWORD_VALIDATION
        ]);

        if ( ! Auth::attempt($credentials)) {

            return response()->json([
                'message' => 'Invalid email or password'
            ], 401);


        }

        $user = $request->user();
        $token = $user->createToken('Access Token');
        $user->access_token = $token->accessToken;

        return response()->json([
            'user' => $user,
            'message' => 'Authenticated successfully'
        ], 200);

    }
}

Postman - Sign Up - Successful

Chrome Inspect Element

View Image Full Size

Postman - Logging In - Error Response

League\OAuth2\Server\Exception\OAuthServerException: Client authentication failed in file /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/league/oauth2-server/src/Exception/OAuthServerException.php on line 154

#0 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/league/oauth2-server/src/Grant/AbstractGrant.php(185): League\OAuth2\Server\Exception\OAuthServerException::invalidClient(Object(Nyholm\Psr7\ServerRequest)) #1 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/laravel/passport/src/Bridge/PersonalAccessGrant.php(21): League\OAuth2\Server\Grant\AbstractGrant->validateClient(Object(Nyholm\Psr7\ServerRequest)) #2 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/league/oauth2-server/src/AuthorizationServer.php(198): Laravel\Passport\Bridge\PersonalAccessGrant->respondToAccessTokenRequest(Object(Nyholm\Psr7\ServerRequest), Object(League\OAuth2\Server\ResponseTypes\BearerTokenResponse), Object(DateInterval)) #3 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/laravel/passport/src/PersonalAccessTokenFactory.php(119): League\OAuth2\Server\AuthorizationServer->respondToAccessTokenRequest(Object(Nyholm\Psr7\ServerRequest), Object(Nyholm\Psr7\Response)) #4 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/laravel/passport/src/PersonalAccessTokenFactory.php(74): Laravel\Passport\PersonalAccessTokenFactory->dispatchRequestToAuthorizationServer(Object(Nyholm\Psr7\ServerRequest)) #5 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/vendor/laravel/passport/src/HasApiTokens.php(67): Laravel\Passport\PersonalAccessTokenFactory->make(1, 'Access Token', Array) #6 /Users/niran/Code/PersonalProjects/dzineer/acme/laravel-8-acme-project/app/Http/Controllers/Api/AuthController.php(70): App\Models\User->createToken('Access Token')

Examples that supposed to work:

Laravel 7|8 REST API with Passport Authentication Tutorial | Supposed to work.

Laravel 8 REST API with Passport Authentication Tutorial Example | Supposed to work.

Has Laravel 8.x changed so that these examples don't work anymore?

Please advise! You Guys are Awesome!!!

Thanks!!!!!

Nov
11
2 months ago
Activity icon

Replied to Always Something Breaking When Using Laravel * Dependency Hell *

HI @snapey If I get the Shift CI + Upgrade Plan does that mean I can shift all, one by one from 5.8 to 9.x ? Is that plan part of this or is their a price for every shift?

Activity icon

Replied to Always Something Breaking When Using Laravel * Dependency Hell *

Thanks for the Reply Talinon, but this was back when 5.8 was all that there was and it was named dev-master. Back then, quite a few years ago, we were not so knowledgeable about how composer worked and about dependency management. Once you use an application/library for some time, you don't always go and see if the library is still available or installable again. Many packages still have dev-master as dependencies but are not in the main composer.json file but in another package's composer.json. Therein lies another problem. There are often cases where the packages start out as dev-master and later get renamed or tagged as some version that are then not compatible with other dependencies that still use for example (laravel's current dev-master).

Nov
10
2 months ago
Activity icon

Started a new Conversation Always Something Breaking When Using Laravel * Dependency Hell *

when we started using Laravel we used Laravel 5.8, but the package was named dev-master at the time that is was available. Now, we still use that version because ... just like any project they get larger and larger with time.

Sometimes we want to add a new library and then something like dependency issue comes up and then we cannot use it because that dependency has changed to another version which breaks Laravel 5.8.

I have once again ran into the problem where our composer.json cannot be rebuilt because laravel changed the version tag to something else and dropped something that it once used.

It seems like they just drop stuff and don't look back. I feel this is a bad approach.

We should always be able to rebuild a project from the composer.json file but we cannot. It seems that there are too many inconsistencies to the point where composer won't even find the correct package and leaves you with a broken project. Even I went back to a previous version and use the previous vendor folder and get a vendor must merge, and I don't know what that means because I removed the vendor folder and then remove the old composer.json and composer.lock file and download the version that worked from github and then place them back and git cannot use it even though it is correct.

Also Laravel changed their tags from what they used to be and thus make the project not buildable anymore.

Where do I go from here?

Any suggestions?

Nov
09
2 months ago
Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Okay, so I could not ever get Database sessions and I don't know why... moving on....

Nov
05
2 months ago
Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

You are right, it is not related to CSRF token as I disabled the Middleware and it still works the same. So then it really does have something to do with the database session.

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Hi @snapey

Here is something interesting

in my blade template I have

<meta name="csrf-token" content="7Oo2Ks3DuoBSdEruffYJeL3Z8mPk6yKtEMDj03DH">

in the login form:

<input type="hidden" name="_token" value="7Oo2Ks3DuoBSdEruffYJeL3Z8mPk6yKtEMDj03DH">

both on same page. After login It can load but one page of any kind (that requires login) and then the token do not match again. The database session driver is using the cookie value for checking if session is valid. You can see that in the previous posts.

To test the theory above, with the blade template, I made the redirect on login go to a page that does not exist. Then I manually go to that url and it loads the page. I then reload the page or go to another URL it will log me out due to a change in session.

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

And @snapey the tokens don't match. I think because it uses file it does not care about if the tokens match or not?

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Hi @snapey yes

SESSION_DRIVER=file

Works.

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

How about this?


    /**
     * Determine if the session and input CSRF tokens match.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function tokensMatch($request)
    {
        $token = $this->getTokenFromRequest($request);

        dnd([
            __METHOD__,
            '$request->session()->all()' => $request->session()->all(),
            '$request->session()->token()' => $request->session()->token(),
            '$request->session()->getAttributes()' => $request->session()->getAttributes(),
            '$request->session()->getVar()' => $request->session()->getVar('_token'),
            '$request->session()->token()' => $token,
            'is_string($request->session()->token())' => is_string($request->session()->token()),
            'is_string($token)' => is_string($token),
        ]);

        return is_string($request->session()->token()) &&
               is_string($token) &&
               hash_equals($request->session()->token(), $token);
    }

output of dnd (same as dd but does not die)

Something is not correct

To Store.php I added:

    /**
     * @return array
     */
    public function getAttributes() {
        return $this->attributes;
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getVar($key) {
        if (isset($this->attributes[$key])) {
            return $this->attributes[$key];
        }
    }
  • When I run getVar('_token') I get _token
  • When I run getAttributes() I get the _token
  • When $request->session()->token() runs it returns null.

here is public function token


    /**
     * Get the CSRF token value.
     *
     * @return string
     */
    public function token()
    {
        return $this->get('_token');
    }

    /**
     * Get an item from the session.
     *
     * @param  string  $key
     * @param  mixed  $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        return Arr::get($this->attributes, $key, $default);
    }

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

I have updated my last post to make it user friendly, more viewable. If you click the View Image Full Size it will load the image in another tab for convenience so you can see it at full size :)

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Hi @snapey, @jeffery, everyone,

Further Investigation

First Request:

Chrome Inspect Element

Chrome Inspect Element

View Image Full Size

Debug Bar

Debug Bar

View Image Full Size

Second Request:

Chrome Inspect Element

Chrome Inspect Element

View Image Full Size

Debug Bar

Debug Bar

View Image Full Size

Database (sessions table)

Chrome Inspect Element

View Image Full Size

So it seems like the session is not keeping. Hope this can help anyone in trying help me troubleshoot this :)

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Hi @snapey @jeffery,

I decided to turn on APP_DEBUG=true and the debugger bar shows:

CSRF token mismatch. /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Does anybody have any suggestions that I can try?

Here is an example of the sessions table

id user_id ip_address user_agent payload last_activity

id: 2eYD4PETxCuk4c75vdSCUUPOgxcwNcJRCuUTV4w0 user_id: NULL ip_address: 172.21.0.1 user_agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) Ap... payload: YToyOntzOjY6Il90b2tlbiI7czo0MDoiNGp2ZmEwRzcyM01iNE... last_activity: 1604584556

Nothing looks out of the ordinary, but for some reason it does not keep the session open... it closes right after login. Is there any reason that could happen?

Any files I can check to see where the behavior is coming from?

I am using Laravel 5.8.

Thanks

Desperately trying to get database sessions working @snapey @jeffery.

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

When using the database:

the sessions table's: user_id field is NULL. Could that help with resolving the problem?

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Here is the config/session.php

<?php

use Illuminate\Support\Str;

return [

    'driver' => env('SESSION_DRIVER', 'database'),

    'lifetime' => env('SESSION_LIFETIME', 120),

    'expire_on_close' => false,

    'encrypt' => false,

    'files' => storage_path('framework/sessions'),

    'connection' => env('SESSION_CONNECTION', null),

    'table' => 'sessions',

    'store' => env('SESSION_STORE', null),

    'lottery' => [2, 100],

    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),

    'path' => '/',

    'domain' => '.example.test',

    'secure' => env('SESSION_SECURE_COOKIE', false),

    'http_only' => false,

    'same_site' => 'lax',

];

If that helps

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Yes, every time. But the cookie value is always changing. So it is not cookie related directly because the cookie is changing no matter what setting I use for SESSION_DRIVER?

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

If I use

SESSION_DRIVER=file

It works.

I has something to do with setting it to

SESSION_DRIVER=database

That is causing this issue.

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Then I clear the cookie and instead I get same issue

Always redirect to login screen

Activity icon

Replied to Can't Keep Session Going When Using SESSION_DRIVER=database

Hi Snapey,

if I do that I get 419 | Page Expired every time.

SESSION_DRIVER=database
#SESSION_DOMAIN=.example.test
 php artisan config:clear

Login again...

419 | Page Expired

Activity icon

Started a new Conversation Can't Keep Session Going When Using SESSION_DRIVER=database

Here is my issue:

.env:

SESSION_DRIVER=database
SESSION_DOMAIN=.example.test

When using the above after every login the next route always redirects to login or expired page.

The session table is always inserting and not using the previous session that was inserted.

Also, when viewing the cookie laravel_session, value is always changed every url load.

if we do .env:

SESSION_DRIVER=file
SESSION_DOMAIN=.example.test

It does not happen, but we want to be able to share session between hosts using same database.

Activity icon

Replied to Sessions Regenerate On Every Request With Database Driver

I am also having a similar issue.

Here is my issue:

.env:

SESSION_DRIVER=database
SESSION_DOMAIN=.example.test

When using the above after every login the next route always redirects to login or expired page.

The session table is always inserting and not using the previous session that was inserted.

Also, when viewing the cookie laravel_session, value is always changed every url load.

if we do .env:

SESSION_DRIVER=file
SESSION_DOMAIN=.example.test

It does not happen, but we want to be able to share session between hosts using same database.

Jul
20
5 months ago
Activity icon

Replied to Compatibility Between Laravel Versions?

It seems to me to irresponsible for Laravel to make such large changes and not give "detailed" guides to tell you exactly what they changed. They just do the thing that most other organizations do: "Just change it and the heck with everyone." This approach has gone on long enough! They need to do things properly. First of all since we depend on composer... they should define what exactly are the dependencies and their versions. Maybe they just code and add libraries that make their code work, but not pay close attention to the dependencies. As you grow in size "Laravel" it does not mean you can "Put caution to the wind." You need to be responsible about your changes and heavily document changes... as your users of your framework, use your framework because they believe in you. Frome 5-8 you have made massive changes causing havik for those who code a lot using your framework. If you cannot honor changes and honor backward compatibility then people will stop using your framework eventually.