Jwt in laravel 6
After installing a fresh laravel 6 we need to follow these steps to secure Rest
Api Using Jwt Token.
Step: 1 Create auth routes
-------------------------------------------------------------
composer require laravel/ui "^1.0" --dev
php artisan ui vue --auth
php artisan migrate
Step: 2 Install jwt package
---------------------------
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
Add service provider in app/app.php inside 'providers'
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
Step 3#: Update your user model
---------------------------
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
Step: 4# Create middleware
---------------------------
php artisan make:middleware AuthJwt
Middleware code
$routeMiddleware in array
'jwtauth' => \App\Http\Middleware\AuthJwt::class,
Api Using Jwt Token.
Step: 1 Create auth routes
-------------------------------------------------------------
composer require laravel/ui "^1.0" --dev
php artisan ui vue --auth
php artisan migrate
Step: 2 Install jwt package
---------------------------
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
Add service provider in app/app.php inside 'providers'
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
Step 3#: Update your user model
---------------------------
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
Step: 4# Create middleware
---------------------------
php artisan make:middleware AuthJwt
Middleware code
$routeMiddleware in array
'jwtauth' => \App\Http\Middleware\AuthJwt::class,
change guard in auth.php
driver' => 'jwt',
Middleware code
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class AuthJwt
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
$user = $this->guard()->userOrFail();
} catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
echo $e->getMessage();
}
return $next($request);
}
public function guard()
{
return Auth::guard('api');
}
}
Step:5# Create Auth controller
---------------------------
php artisan make:controller AuthController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = request(['email', 'password']);
if (! $token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Invalid Credentials'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json($this->guard()->user());
}
/**
* Log the user out (Invalidate the token)
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
$this->guard()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken($this->guard('api')->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' => $this->guard('api')->factory()->getTTL() * 60
]);
}
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\Guard
*/
public function guard()
{
return Auth::guard('api');
}
}
?>
Step 6#: Adding auth routes
--------------------------------
Route::post('login', 'AuthController@login');
Route::get('me', 'AuthController@me')->middleware('jwtauth');
Route::get('logout', 'AuthController@logout');
Route::get('refresh', 'AuthController@refresh');
Postman testing
No comments:
Post a Comment