JWT Authentication (Laravel Part )

composer require tymon/jwt-auth
//inside providers'providers' => [
//inside aliases'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class, 'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret //this will create JWT key inside env file
php artisan make:middleware JwtMiddleware
<?phpnamespace App\Http\Middleware;use Closure;use Exception;use JWTAuth;use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;class JwtMiddleware extends BaseMiddleware{/*** Handle an incoming request.** @param \Illuminate\Http\Request $request* @param \Closure $next* @return mixed*/public function handle($request, Closure $next){try {$user = JWTAuth::parseToken()->authenticate();} catch (Exception $e) {if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {return response()->json([‘status’ => ‘Token is Invalid’]);} else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {return response()->json([‘status’ => ‘Token is Expired’]);} else {return response()->json([‘status’ => ‘Authorization Token not found’]);}}return $next($request);}}
protected $routeMiddleware = [ ...
'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
]; ...
Route::post('login', [AuthController::class, 'authenticate']);Route::post('register', [AuthController::class, 'register']);Route::group(['middleware' => ['jwt.verify']], function () {Route::get('logout', [AuthController::class, 'logout']);Route::get('get_user', [AuthController::class, 'get_user']);});
php artisan make:controller AuthController
<?phpnamespace App\Http\Controllers;use JWTAuth;use App\Models\User;use Illuminate\Http\Request;use Tymon\JWTAuth\Exceptions\JWTException;use Symfony\Component\HttpFoundation\Response;use Illuminate\Support\Facades\Validator;class AuthController extends Controller{public function register(Request $request){//Validate data$data = $request->only('name', 'email', 'password');$validator = Validator::make($data, ['name' => 'required|string','email' => 'required|email|unique:users','password' => 'required|string|min:6|max:50']);//Send failed response if request is not validif ($validator->fails()) {return response()->json(['error' => $validator->messages()], 400);}//Request is valid, create new user$user = User::create(['name' => $request->name,'email' => $request->email,'password' => bcrypt($request->password)]);//User created, return success responsereturn response()->json(['success' => true,'message' => 'User created successfully','data' => $user], Response::HTTP_OK);}public function authenticate(Request $request){$credentials = $request->only('email', 'password');//valid credential$validator = Validator::make($credentials, ['email' => 'required|email','password' => 'required|string|min:6|max:50']);//Send failed response if request is not validif ($validator->fails()) {return response()->json(['error' => $validator->messages()], 400);}//Request is validated//Crean tokentry {if (! $token = JWTAuth::attempt($credentials)) {return response()->json(['success' => false,'message' => 'Login credentials are invalid.',], 400);}} catch (JWTException $e) {return $credentials;return response()->json(['success' => false,'message' => 'Could not create token.',], 500);}//Token created, return with success response and jwt tokenreturn response()->json(['success' => true,'token' => $token,]);}public function logout(Request $request){//valid credential$validator = Validator::make($request->only('token'), ['token' => 'required']);//Send failed response if request is not validif ($validator->fails()) {return response()->json(['error' => $validator->messages()], 400);}//Request is validated, do logouttry {JWTAuth::invalidate($request->token);return response()->json(['success' => true,'message' => 'User has been logged out']);} catch (JWTException $exception) {return response()->json(['success' => false,'message' => 'Sorry, user cannot be logged out'], Response::HTTP_INTERNAL_SERVER_ERROR);}}public function get_user(Request $request){$this->validate($request, ['token' => 'required']);$user = JWTAuth::authenticate($request->token);return response()->json(['user' => $user]);}}
<?phpnamespace App\Models;use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Tymon\JWTAuth\Contracts\JWTSubject;class User extends Authenticatable implements JWTSubject{use HasFactory, 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 [];}}
php artisan migrate




A Programmer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Join us for 2022's First Mambo Merge Office Hours!

Why 1Password is the best password manager for Windows 10?

API3 API Integrations Report — September 2021

Listening to the Home Assistent Websocket API with Python

Start with GitHub !

No one cares about the language you use


Power Up Implication

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bachir Khoder

Bachir Khoder

A Programmer

More from Medium

RBAC with Laravel 9

Laravel 8 Group By Query Example

Setup Redis on Laravel project 💡

Laravel API CRUD with validation