JWT Authentication in Laravel 5.8


NOTE:
php artisan make:auth
php artisan migrate
-------------------------
Step 1: Install the JWT package
composer require tymon/jwt-auth 1.0.*

Step 2: Publish config
php artisan vendor:publish --provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider”

Step 3: Create JWT secret key
php artisan jwt:secret

Step 4: Modify User Model
----------------------------------------
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
   use Notifiable;

   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
       'name', 'email', 'password',
   ];

   /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
   protected $hidden = [
       'password', 'remember_token',
   ];

   /**
    * The attributes that should be cast to native types.
    *
    * @var array
    */
   protected $casts = [
       'email_verified_at' => 'datetime',
   ];

   /**
    * Get the identifier that will be stored in the subject claim of the JWT.
    *
    * @return mixed
    */
   public function getJWTIdentifier()
   {
       return $this->getKey();
   }

   /**
    * Return a key value array, containing any custom claims to be added to the JWT.
    *
    * @return array
    */
   public function getJWTCustomClaims()
   {
       return [];
   }

   public function setPasswordAttribute($password)
   {
       if ( !empty($password) ) {
           $this->attributes['password'] = bcrypt($password);
       }
   }
}
------------------------------------------------------------
Step 5: Configure Auth
-------------------------------------------
'defaults' => [
     'guard' => 'api',
     'passwords' => 'users',
],
   
'guards' => [
     'web' => [
         'driver' => 'session',
         'provider' => 'users',
     ],

     'api' => [
         'driver' => 'jwt',
         'provider' => 'users',
     ],
],

Step 6: Make AuthController( Then we put the following code in the file.)

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
   /**
    * Get a JWT via given credentials.
    *
    * @return \Illuminate\Http\JsonResponse
    */
   public function login()
   {
       $credentials = request(['email', 'password']);

       if (! $token = auth()->attempt($credentials)) {
           return response()->json(['error' => 'Unauthorized'], 401);
       }

       return $this->respondWithToken($token);
   }

   /**
    * Get the authenticated User.
    *
    * @return \Illuminate\Http\JsonResponse
    */
   public function me()
   {
       return response()->json(auth()->user());
   }

   /**
    * Log the user out (Invalidate the token).
    *
    * @return \Illuminate\Http\JsonResponse
    */
   public function logout()
   {
       auth()->logout();

       return response()->json(['message' => 'Successfully logged out']);
   }

   /**
    * Refresh a token.
    *
    * @return \Illuminate\Http\JsonResponse
    */
   public function refresh()
   {
       return $this->respondWithToken(auth()->refresh());
   }

   /**
    * Get the token array structure.
    *
    * @param  string $token
    *
    * @return \Illuminate\Http\JsonResponse
    */
   protected function respondWithToken($token)
   {
       return response()->json([
           'access_token' => $token,
           'token_type' => 'bearer',
           'expires_in' => auth()->factory()->getTTL() * 60
       ]);
   }
}
--------------------------------------------------------
Step 7: Add Routes (routes/api.php)

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
   return $request->user();
});

Route::group([

   'middleware' => 'api',

], function ($router) {

   Route::post('login', 'AuthController@login');
   Route::post('logout', 'AuthController@logout');
   Route::post('refresh', 'AuthController@refresh');
   Route::post('me', 'AuthController@me');
});

-------------------------------------------------------------------------------
Step 8:  Make 
php artisan make:controller UserController
Next put the following code into the controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use App\User;

class UserController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index()
   {
       $users = User::all();

       return $users;
   }

   /**
    * Store a newly created resource in storage.
    *
    */
   public function store(Request $request)
   {
       $userData = $request->all();
       $user = User::create($userData);

       return $user;
   }
}

Step 9: Lets modify our routes/api.php to include the following code
Route::post(‘users’, ‘UserController@store’);
Route::get(‘users’, ‘UserController@index’);


Postman ScreenShot





Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment