In this post, I am going to explain “how to create rest api with authentication using passport” in laravel 6 application. Rest API is must be used when you are working with mobile application. when your application is preferred for a web app and the mobile app then you must have to create API for your mobile app development.
However, Laravel provides an easy way to create Rest API using the passport package. if you need to authentication in your mobile app then you can easily do it using a passport. Laravel 6 Passport provides a way to create an auth token for validating users.
Web services
web service is very important when you are creating web and mobile apps.
How to Create Rest API with Authentication Using Passport
If you require to create API for mobile application As we know laravel is the most popular framework for API creation. If you are beginners and don’t know what is API and web services then you are the right place. In this article I will show how to create API and Authentication for mobile APPs.i will show you step by step build restful API authentication using eloquent API resources in laravel 6.
Follow bellow a few steps to create a restful API example in laravel 6 app.
- Register API
- Login API
- User Details API
Above three API, you can simply get by following a few steps. It is from scratch so just follow the below steps, at last, I attach a screenshot of the API test.
Step 1:- In the first step required to install fresh laravel using below command, So open your terminal or command prompt and run command.
1 2 3 | composer create-project --prefer-dist laravel/laravel APITest |
Step 2:- In this step to get install the passport package in laravel using below command
1 2 3 | composer require laravel/passport |
After passport installation package open config/app.php file and add service provider
1 2 3 | LaravelPassportPassportServiceProvider::class, |
Step 3:- The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after registering the provider. The Passport migrations will create the tables your application needs to store clients and access tokens.
1 2 3 | php artisan migrate |
Next, you should run the passport:install
command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokens.
1 2 3 | php artisan passport:install |
Step 4:- In this step we have to configure passport, So just follow three given file changes.
firest we need to add the LaravelPassportHasApiTokens
trait to your AppUser
model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user’s token and scopes.
App/User.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?php namespace App; use LaravelPassportHasApiTokens; use IlluminateNotificationsNotifiable; use IlluminateFoundationAuthUser as Authenticatable; class User extends Authenticatable { use HasApiTokens, 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', ]; } |
app/Providers/AuthServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php namespace AppProviders; use LaravelPassportPassport; use IlluminateSupportFacadesGate; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'AppModel' => 'AppPoliciesModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); } } |
config/auth.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php return [ ..... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], ..... ] |
Step 5:- In this step, We will create API routes laravel provide api.php file for write web services routes So lets add new routes on that file.
routes/api.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php /* |-------------------------------------------------------------------------- | 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::post('login', 'APIUserController@login'); Route::post('register', 'APIUserController@register'); Route::group(['middleware' => 'auth:api'], function(){ Route::post('details', 'APIUserController@details'); }); |
Step 6:- In this step first we have create new directory API on controller folder and create new controller in API directory, So let’s create UserController and put below code.
app/Http/Controllers/API/UserController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | <?php namespace AppHttpControllersAPI; use IlluminateHttpRequest; use AppHttpControllersController; use AppUser; use IlluminateSupportFacadesAuth; use Validator; class UserController extends Controller { public $successStatus = 200; /** * login api * * @return IlluminateHttpResponse */ public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $success['token'] = $user->createToken('MyApp')->accessToken; return response()->json(['success' => $success], $this->successStatus); } else{ return response()->json(['error'=>'Unauthorised'], 401); } } /** * Register api * * @return IlluminateHttpResponse */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'c_password' => 'required|same:password', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $success['token'] = $user->createToken('MyApp')->accessToken; $success['name'] = $user->name; return response()->json(['success'=>$success], $this->successStatus); } /** * details api * * @return IlluminateHttpResponse */ public function details() { $user = Auth::user(); return response()->json(['success' => $user], $this->successStatus); } } |
Now we are ready to run our API, So run below command
1 2 3 | php artisan serve |
Now, we can simply test API using postman tool, I have test it and you can see screenshot.
Read Also: Laravel Passport Auth
Register:-
Login:-
getDetails:-
We hope this article is very helpful for creating API using passport for mobile application.
Thanks !!
I’m a full-stack developer. My hobby and profession to write blog and programming tips that helps to others. I am a great admirer of PHP, Laravel, Codeigniter, AngularJS, Vue.js, Javascript, JQuery, WordPress, Plugin Development, Theme Development and Bootstrap from the early stage.