jwt authentication laravel react code example

Example 1: laravel token authentication

# Database Preparation
// add api_token to users table
Schema::table('users', function ($table) {
    $table->string('api_token', 80)->after('password')
                        ->unique()
                        ->nullable()
                        ->default(null);
});

// Create token for existing users, code can also be added to registerController
    $token = Str::random(60);
    $user = User::find(1);
    $user->api_token = hash('sha256', $token); // <- This will be used in client access
    $user->save();



//config/auth.php
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token', // <- Add this entry
            'provider' => 'users',
            'hash' => false,
        ],
    ],

          
          
//routes/api.php
    // Add "middleware('auth:api')" as below        
	Route::middleware('auth:api')->get('/user', function (Request $request) {
        return $request->user();
    });          



//client access example (in Vue js)

axios.get('http://example.com/api/user', 
          {
  headers: { 
    'Accept': 'application/json', 
    'Authorization': 'Bearer '+ 'user-api-token'
  }
}
         )
  .then(function (response) {
  // handle success
  console.log(response);
})
  .catch(function (error) {
  // handle error
  console.log(error);
})

Example 2: 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);
}

Tags:

Misc Example