Laravel / Advanced / Auth using Passport
Auth using passport
-
STEP 1
1. package
composer require laravel/passport php artisan migrate Next, generate token keys for strengthening the security and restrain hackers from deteriorating the security of our applications.
php artisan passport:install 2. Configure Passport Module
app/Models/User.php
namespace 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 Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasFactory, Notifiable, HasApiTokens; /** * 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', ]; } Next, open app/Providers/AuthServiceProvider.php file and register the registerPolicies() method inside the boot() function, It will evoke the required routes.
namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate; use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Models\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); } } Register the PassportServiceProvider class in providers array inside the config/app.php file:
'providers' => [ ... ... ... Laravel\Passport\PassportServiceProvider::class, ], Configure driver for the Passport, get inside the config/auth.php file and make the changes as shown below.
return [ .... .... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], .... .... ] 3. Create Posts Model & Run Migration
php artisan make:model Post -m 4. Controller
PassportAuthController.phpphp artisan make:controller PassportAuthController
PostController.phpnamespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class PassportAuthController extends Controller { /** * Registration */ public function register(Request $request) { $this->validate($request, [ 'name' => 'required|min:4', 'email' => 'required|email', 'password' => 'required|min:8', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password) ]); $token = $user->createToken('LaravelAuthApp')->accessToken; return response()->json(['token' => $token], 200); } /** * Login */ public function login(Request $request) { $data = [ 'email' => $request->email, 'password' => $request->password ]; if (auth()->attempt($data)) { $token = auth()->user()->createToken('LaravelAuthApp')->accessToken; return response()->json(['token' => $token], 200); } else { return response()->json(['error' => 'Unauthorised'], 401); } } } php artisan make:controller PostController namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller { public function index() { $posts = auth()->user()->posts; return response()->json([ 'success' => true, 'data' => $posts ]); } public function show($id) { $post = auth()->user()->posts()->find($id); if (!$post) { return response()->json([ 'success' => false, 'message' => 'Post not found ' ], 400); } return response()->json([ 'success' => true, 'data' => $post->toArray() ], 400); } public function store(Request $request) { $this->validate($request, [ 'title' => 'required', 'description' => 'required' ]); $post = new Post(); $post->title = $request->title; $post->description = $request->description; if (auth()->user()->posts()->save($post)) return response()->json([ 'success' => true, 'data' => $post->toArray() ]); else return response()->json([ 'success' => false, 'message' => 'Post not added' ], 500); } public function update(Request $request, $id) { $post = auth()->user()->posts()->find($id); if (!$post) { return response()->json([ 'success' => false, 'message' => 'Post not found' ], 400); } $updated = $post->fill($request->all())->save(); if ($updated) return response()->json([ 'success' => true ]); else return response()->json([ 'success' => false, 'message' => 'Post can not be updated' ], 500); } public function destroy($id) { $post = auth()->user()->posts()->find($id); if (!$post) { return response()->json([ 'success' => false, 'message' => 'Post not found' ], 400); } if ($post->delete()) { return response()->json([ 'success' => true ]); } else { return response()->json([ 'success' => false, 'message' => 'Post can not be deleted' ], 500); } } } 4. Define API Routes
Route::post('register', [PassportAuthController::class, 'register']); Route::post('login', [PassportAuthController::class, 'login']); Route::middleware('auth:api')->group(function () { Route::resource('posts', PostController::class); }); -
STEP 2 :Testing
1. Register
url : http://localhost:8000/api/register
method: post
in header : "Accept": application/json
body : raw & json
{"name" : "manoj", "email" : "m@gmail.com", "password" : "123456789"} 2. Login
url : http://localhost:8000/api/login
method: post
in header : "Accept": application/json
body : raw & json
{ "email" : "m@gmail.com", "password" : "123456789"} 3. Posts
url : http://localhost:8000/api/posts
method: post
in header
'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer '. $accessToken, ] body : raw & json
{ "title" : "m@gmail.com", "description" : "123456789"}