Laravel Passport – Create REST API with authentication
In this post we will give you information about Laravel Passport – Create REST API with authentication. Hear we will give you detail about Laravel Passport – Create REST API with authenticationAnd how to use it also give you demo for it if it is necessary.
Today, in this tutorial we are share with you hhow to use laravel passport authentication in your laravel application. Laravel already provide simple auth system for web. but what about APIs? APIs basically use token for authentication. when any user login thenn generate one tocken and it is use for authentication purpose. so, laravel provide Passport for APIs authentication.
How to use Passport in laravel for built RESTful APIs and how to configure in laravel application. here we are expain all things in step by step in very easy way and with example.
In this tutorial we are built following APIs service using Passpost
1. Register API
2. Login API
3. Get User Details API
Simply follow this step and you can easyly integrate Passport in your laravel application.
Step – 1 : Installation
First we need to install laravel’s Passport package in your application using run following command
composer require laravel/passport
Step – 2 : Configure Pacckage
After install successfully Passport package in our application we need to set their Service Provider. so, open your config/app.php file and add following provider in it.
'providers' => [
....
LaravelPassportPassportServiceProvider::class,
],
Step – 3 : Run Migration And Install
After set service provider then run migration. passport migration tables use for store client and tokens.
php artisan migrate
Next to you should install passport, because generate encryption keys needs to usse in create passport token.
php artisan passport:install
Step – 4 : Passport Configure
After done above proccess then we need to make some changes for configure passport setting.
1. In model we added HasApiTokens class of Passport,
2. In AuthServiceProvider we added “Passport::routes()”,
3. In auth.php, we added api auth configuration.
1. app/User.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',
];
}
2. app/Providers/AuthServiceProvider.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();
}
}
3. config/auth.php
return [
.....
.....
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
.....
.....
]
Step – 5 : Create Route
Next, create following route in routes/api.php file. this route file generally use for create APIs route.
Route::post('login', 'API[email protected]');
Route::post('register', 'API[email protected]');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('get-details', 'API[email protected]');
});
[ADDCODE]
Step – 6 : Create Controller
Next, we should create one PassportController.php controller in app/Http/Controllers/API/ root.
We are create one API folder in Controllers for store all APIs controller in it.
app/Http/Controllers/API/PassportController.php
namespace AppHttpControllersAPI;
use IlluminateHttpRequest;
use AppHttpControllersController;
use AppUser;
use IlluminateSupportFacadesAuth;
use Validator;
class PassportController 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 getDetails()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
}
Allright, our APIs creation proccess done now we are testing it. so simple run laravel app by following command
php artisan serve
Step – 7 : APIs Testing
Now, we are test all API in any API testing tool, we are use Postman for testing APIs
1. Register API
2. Login API
3. Get Detailss API
Now, we will test details api, In this api you have to set two header as listed bellow:
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
We are hope this tutorial help you….
Hope this code and post will helped you for implement Laravel Passport – Create REST API with authentication. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs