laravel authentication with jwt code example

Example 1: jwt laravel

php artisan jwt:secret

Example 2: laravel 6 tymon/jwt-auth

composer require tymon/jwt-auth

Example 3: vanilla javascript jwt authentication laravel

In my guest RedirectIfAuthenticated middleware check for cookie, if exists, setToken which in turn sets Guard to Authenticated and will always redirect to /home if token is available and valid:

public function handle($request, Closure $next, $guard = null)
{
    if ($request->hasCookie('access_token')) {
        Auth::setToken($request->cookie('access_token'));
    }

    if (Auth::guard($guard)->check()) {
        return redirect('/home');
    }

    return $next($request);
}

And In my post-auth Routes middleware I also setToken and if its valid and exists, will allow access, otherwise will throw a range of JWT errors which just redirect to pre-auth view:

public function handle($request, Closure $next)
{
    JWTAuth::setToken($request->cookie('access_token'))->authenticate();

    return $next($request);
}

Example 4: laravel JWTAuthentication

$ composer require tymon/jwt-auth:dev-develop --prefer-source

Example 5: jwt laravel

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Tags:

Php Example